Java “constant string too long” compile error. Only happens using Ant, not when using Eclipse

前端 未结 11 2105
抹茶落季
抹茶落季 2020-12-01 15:25

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

相关标签:
11条回答
  • 2020-12-01 16:15

    I was able to resolve this issue in a similar way like Lukas Eder.

    String testXML = "REALLY LONG STRING...............................";
           textXML += "SECOND PART OF REALLY LONG STRING..........";
           textXML += "THIRD PART OF REALLY LONG STRING............";
    

    Just split it up and add it together;

    0 讨论(0)
  • 2020-12-01 16:16

    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")));
    
    0 讨论(0)
  • 2020-12-01 16:16

    A workaround is to chunk your string using new String() (yikes) or StringBuilder, e.g.

    String CONSTANT = new String("first chunk") 
                    + new String("second chunk") + ... 
                    + new String("...");
    

    Or

    String CONSTANT = new StringBuilder("first chunk")
                    .append("second chunk")
                    .append("...")
                    .toString();
    

    These can be viable options if you're producing this string e.g. from a code generator. The workaround documented in this answer where string literals are concatenated no longer works with Java 11

    0 讨论(0)
  • 2020-12-01 16:17

    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!!!" 
    } );
    
    0 讨论(0)
  • 2020-12-01 16:22

    You can try this,

    public static final String CONSTANT = new StringBuilder("Your really long string").toString();
    
    0 讨论(0)
提交回复
热议问题