java - 如何处理一个823237个字符的字符串

标签 java string servlets file-io io

我有一个包含 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/

相关文章:

java - 如何在 java servlet 中链接外部 css?

java - 这个 "method linking"对其他组件的(最佳)名称或描述是什么

java - 如何根据括号分割字符串并避免空格

java - 删除 class= 属性

python - 无和空字符串的 CSV 阅读器行为

java - JSP 页面是/否对话框

java - 我的 url 映射转移了我的 CSS 页面

java - 是否有 java 类文件/字节码编辑器来编辑指令?

java - 在java中从客户端向服务器发送字符串时出现问题

java - 如何从InputStream中获取Base64字符串?