Java “constant string too long” compile error. Onl

2019-01-09 14:16发布

I have a few really long strings in one class for initializing user information. When I compile in Eclipse, I don't get any errors or warnings, and the resulting .jar runs fine.

Recently, I decided to create an ant build file to use. Whenever I compile the same class with ant, I get the "constant string too long" compile error. I've tried a number of ways to set the java compiler executable in ant to make sure that I'm using the exact same version as in Eclipse.

I'd rather figure out how to get the same successful compile I get in Eclipse in Ant than try to rework the code to dynamically concatenate the strings.

标签: java eclipse ant
9条回答
beautiful°
2楼-- · 2019-01-09 14:50

I found I could use the apache commons lang StringUtils.join( Object[] ) method to solve this.

public static final String CONSTANT = org.apache.commons.lang.StringUtils.join( new String[] {
  "This string is long", 
  "really long...", 
  "really, really LONG!!!" 
} );
查看更多
爷、活的狠高调
3楼-- · 2019-01-09 14:51

Another trick, if I'm determined to put a long string in the source, is to avoid the compiler detecting it as a constant expression.

String dummyVar = "";
String longString = dummyVar +
    "This string is long\n" + 
    "really long...\n" + 
    "really, really LONG!!!";

This worked for a while, but if you keep going too far the next problem is a stack overflow in the compiler. This describes the same problem and, if you're still determined, how to increase your stack - the problem seems to be the sheer size of the method now. Again this wasn't a problem in Eclipse.

查看更多
来,给爷笑一个
4楼-- · 2019-01-09 14:52

Nothing of above worked for me. I have created one text file with name test.txt and read this text file using below code

String content = new String(Files.readAllBytes(Paths.get("test.txt")));
查看更多
聊天终结者
5楼-- · 2019-01-09 14:53

Add your string to values/strings.xml than call getResources.getString(R.string.yourstring)

查看更多
一纸荒年 Trace。
6楼-- · 2019-01-09 15:05

You can try this,

public static final String CONSTANT = new StringBuilder("Your really long string").toString();
查看更多
ら.Afraid
7楼-- · 2019-01-09 15:07
  String theString2 = IOUtils.toString(new FileInputStream(new     
  File(rootDir + "/properties/filename.text")), "UTF-8");
查看更多
登录 后发表回答