问题描述
|
需要显示100,000个字符的文本。如果将其放入String对象,则会收到错误消息“常量字符串太长”。与StringBuffer对象相同。
StringBuffer stringBuffer = new StringBuffer();
stringBuffer.append(\"Long text here........\"); //<-- error
除了将文本切成较小的文本之外,还有解决方案吗?
解决方法
我认为Java中常量字符串的长度限制为64K,但是,您可以在运行时构造一个大于64K的字符串。
, 长度不能超过64k的字符串不能直接在java中使用,但是可以间接使用它们。
步骤1)单击您的字符串
步骤2)同时按Alt + Enter键
步骤3)选择“提取字符串”资源
步骤4)命名资源,然后按Enter键。
这就对了。它将在ѭ1中为您生成一个字符串
如果您的ѭ1中已经有字符串,则可以使用以下代码进行检索:
String yourStr = getString(R.string.sampleBigString);
, 是的,常量字符串在Java中有一个限制。
因此,您可以做的是将您的String复制到一个文本文件中,并放入Assets文件夹的根目录,然后通过以下方法从文件中读取。
public String ReadFromfile(String fileName,Context context) {
StringBuilder returnString = new StringBuilder();
InputStream fIn = null;
InputStreamReader isr = null;
BufferedReader input = null;
try {
fIn = context.getResources().getAssets()
.open(fileName,Context.MODE_WORLD_READABLE);
isr = new InputStreamReader(fIn);
input = new BufferedReader(isr);
String line = \"\";
while ((line = input.readLine()) != null) {
returnString.append(line);
}
} catch (Exception e) {
e.getMessage();
} finally {
try {
if (isr != null)
isr.close();
if (fIn != null)
fIn.close();
if (input != null)
input.close();
} catch (Exception e2) {
e2.getMessage();
}
}
return returnString.toString();
}
, 我遇到了同样的问题,解决方案是将一个很大的字符串常量分配给一个常量,然后将其拆分为几个较小的常量,这些常量分配给新常量并将它们连接起来。
例:
无法编译的非常大的字符串:
private static String myTooBigText = \"...\";
将其拆分为几个常量,然后将它们串联起来进行编译:
private static String mySmallText_1 = \"...\";
private static String mySmallText_2 = \"...\";
...
private static String mySmallText_n = \"...\";
private static String myTooBigText = mySmallText_1 + mySmallText_2 + ... + mySmallText_n;