我有一个包含 823237 个字符的字符串。它实际上是一个 xml 文件,出于测试目的,我想作为响应从 servlet 返回。
我已经尝试了所有我能想到的
1)用整个字符串创建一个常量......在这种情况下Eclipse提示(在servlet类名下有一条红线) -
The type generates a string that requires more than 65535 bytes to encode in Utf8 format in the constant pool
2) 将整个字符串分成 20 个字符串常量并写入
out
直接对象就像是 :
out.println( CONSTANT_STRING_PART_1 + CONSTANT_STRING_PART_2 +
CONSTANT_STRING_PART_3 + CONSTANT_STRING_PART_4 +
CONSTANT_STRING_PART_5 + CONSTANT_STRING_PART_6 +
// add all the string constants till .... CONSTANT_STRING_PART_20);
在这种情况下......构建失败......提示......
[javac] D:\xx\xxx\xxx.java:87: constant string too long
[javac] CONSTANT_STRING_PART_19 + CONSTANT_STRING_PART_20);
^
3) 将 xml 文件作为字符串读取并写入
out object
..在这种情况下我得到SEVERE: Allocate exception for servlet MyServlet
Caused by: org.apache.xmlbeans.XmlException: error: Content is not allowed in prolog.
最后我的问题是......我怎样才能从
servlet
返回这么大的字符串(作为响应) ???
最佳答案
您可以避免使用流加载内存中的所有文本:
InputStream is = new FileInputStream("path/to/your/file"); //or the following line if the file is in the classpath
InputStream is = MyServlet.class.getResourceAsStream("path/to/file/in/classpath");
byte[] buff = new byte[4 * 1024];
int read;
while ((read = is.read(buff)) != -1) {
out.write(buff, 0, read);
}
关于java - 如何处理一个823237个字符的字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10798769/