如何处理823237个字符的字符串

Hel*_*Boy 2 java string io file-io servlets

我有一个字符串,其中包含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
Run Code Online (Sandbox Code Playgroud)

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); 
Run Code Online (Sandbox Code Playgroud)

在这种情况下...构建失败..抱怨..

   [javac] D:\xx\xxx\xxx.java:87: constant string too long
   [javac]      CONSTANT_STRING_PART_19 + CONSTANT_STRING_PART_20); 
                                                    ^
Run Code Online (Sandbox Code Playgroud)

3)将xml文件作为字符串读取并写入out object..在这种情况下我得到

SEVERE: Allocate exception for servlet MyServlet
Caused by: org.apache.xmlbeans.XmlException: error: Content is not allowed in prolog.
Run Code Online (Sandbox Code Playgroud)

最后我的问题是......我怎样才能从servlet???中返回如此大的字符串(作为响应)?

Teg*_*Teg 5

您可以避免使用流加载内存中的所有文本:

    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);  
    }
Run Code Online (Sandbox Code Playgroud)