Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

String error "constant string too long"

Tags:

android

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?

like image 283
sandalone Avatar asked Jun 11 '11 21:06

sandalone


People also ask

How do you resolve a constant string too long?

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.

What is maximum length of string in Java?

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.

How do you declare a string constant in Java?

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.


3 Answers

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;
like image 70
jascadev Avatar answered Oct 23 '22 10:10

jascadev


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;
like image 34
jascadev Avatar answered Oct 23 '22 09:10

jascadev


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.

like image 32
Sai Avatar answered Oct 23 '22 08:10

Sai