How to process a string with 823237 characters

file-io, io, java, servlets, string

Solution

The second approach might work the following way:

out.print(CONSTANT_STRING_PART_1);
out.print(CONSTANT_STRING_PART_2);
out.print(CONSTANT_STRING_PART_3);
out.print(CONSTANT_STRING_PART_4);
// ...
out.print(CONSTANT_STRING_PART_N);
out.println();

You can do this in a loop of course (which is highly recommended ;)).

The way you do it, you just temporarely create the large string again to then pass it to `println()`, which is the same problem as the first one.

Problem

I have a string that has 823237 characters in it. its actually an xml file and for testing purpose I want to return as a response form a servlet. I have tried everything I can possible think of 1) creating a constant with the whole string... in this case Eclipse complains (with a red line under servlet class name) - ``` The type generates a string that requires more than 65535 bytes to encode in Utf8 format in the constant pool ``` 2) breaking the whole string into 20 string constants and writing to the `out` object directly something like : ``` 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); ``` in this case ... the build fails .. complaining.. ``` [javac] D:\xx\xxx\xxx.java:87: constant string too long [javac] CONSTANT_STRING_PART_19 + CONSTANT_STRING_PART_20); ^ ``` 3) reading the xml file as a string and writing to `out object` .. in this case I get ``` SEVERE: Allocate exception for servlet MyServlet Caused by: org.apache.xmlbeans.XmlException: error: Content is not allowed in prolog. ``` Finally my question is ... how can I return such a big string (as response) from the `servlet` ???

Original source