There is a 100,000-character text that need to be displayed. If I put it into String object, I get an error "constant string too long". The same is with StringBuffer object.
StringBuffer stringBuffer = new StringBuffer();
stringBuffer.append("Long text here........"); //<-- error
Is there a solution to this beside cutting the text into smaller texts?
Solving the Problem The best way is to store our string in a separate file instead of in a declared variable or constant. Of course, we could also introduce concatenation with our string, but such isn't recommended.
Therefore, the maximum length of String in Java is 0 to 2147483647. So, we can have a String with the length of 2,147,483,647 characters, theoretically.
So to declare a constant in Java you have to add static final modifiers to a class field. Example: public static final String BASE_PATH = "/api"; You should follow Java constant naming convention – all constant variables should be in upper case, words should be separated by the underscore.
I had same problem and the solution was the very big string literal that was assigned to one constant, to split it to several smaller literals assigned to new constants and concatenate them.
Example:
Very big string that can not compile:
private static String myTooBigText = "...";
Split it to several constants and concatenate them that compiles:
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;
I had same problem and the solution was the very big string literal that was assigned to one constant, to split it to several smaller literals assigned to new constants and concatenate them.
Example:
Very big string that can not compile:
private static String myTooBigText = "...";
Split it to several constants and concatenate them that compiles:
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;
I think the length of constant strings in java is limited to 64K -- however, you could construct a string at run time that is bigger than 64K.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With