Gooshi Roy
Gooshi Roy

Reputation: 11

Any way to override "Constant String too Long" without concatenating strings?

I have a long program that requires a rudimentary declaration of 2 strings, str1 and str2. However, when using data, I get a "constant string too long" error in Java. Is there any way to bypass this without breaking up the strings and concatenating them?

Upvotes: 1

Views: 9142

Answers (1)

WillShackleford
WillShackleford

Reputation: 7018

The following code would read the string from a resource as Kayaman suggested, assuming your string is put in the file mystring.txt in the same directory as MyClass.java and lines are separated with \n. MyClass.class needs to be changed to the name of your class.

private static String myString = null;

public static String getMyString() throws IOException {
    if (null == myString) {
        try (BufferedReader br = new BufferedReader(new InputStreamReader(MyClass.class.getResourceAsStream("mystring.txt")))) {
            myString = br.lines().collect(Collectors.joining("\n"));
        }
    }
    return myString;
}

public static void main(String[] args) throws IOException {
    String str = getMyString();
    System.out.println("str = " + str);
}

Upvotes: 1

Related Questions