65

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.

Allan
  • 1,635
  • 4
  • 15
  • 19
  • 4
    your string is too long, as you may realize. as a hack you can split it into multiple strings in your source code and concatenate them. this is what the eclipse java compiler is doing on your behalf. – Ron Feb 23 '11 at 21:54

12 Answers12

49

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!!!" 
} );
mrswadge
  • 1,659
  • 1
  • 20
  • 43
  • 4
    I find this a relly neat solution when I need to test something quickly – Miki Jun 01 '16 at 10:41
  • 2
    Thank you,You save my day :) – Hamid Nov 24 '16 at 17:49
  • 2
    I realised that this answer doesn't really answer the original posters question, it is only a workaround. I wouldn't recommend it for production code, only for quick and dirty testing purposes. – mrswadge Sep 19 '17 at 16:53
  • FWIW I voted up the answer by teabot here https://stackoverflow.com/a/2738598/1247302 – mrswadge Sep 23 '21 at 20:52
48

Someone is trying to send you a message :-) In the time you've spend fiddling with compiler versions you could have loaded the data from a text file - which is probably where it belongs.

Check out:

HendraWD
  • 2,984
  • 2
  • 31
  • 45
teabot
  • 15,358
  • 11
  • 64
  • 79
19

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")));
Amol Suryawanshi
  • 2,108
  • 21
  • 29
  • This is the best choice I guess, to store the content in a separate file instead of in java source code itself. – Eric Aug 13 '20 at 08:15
  • I had a bit trouble getting this code to work. See https://howtodoinjava.com/java/io/java-read-file-to-string-examples/ for the full code with .readAllBytes and the stuff you have to import - it helped me. – Rublacava Sep 02 '20 at 01:56
8

The length of a string constant in a class file is limited to 2^16 bytes in UTF-8 encoding, this should not be dependent on the compiler used. Perhaps you are using a different character set in your ant file than in eclipse, so that some characters need more bytes than before. Please check the encoding attribute of your javac task.

Jörn Horstmann
  • 33,639
  • 11
  • 75
  • 118
4

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

Lukas Eder
  • 211,314
  • 129
  • 689
  • 1,509
2
  String theString2 = IOUtils.toString(new FileInputStream(new     
  File(rootDir + "/properties/filename.text")), "UTF-8");
Monis Majeed
  • 1,358
  • 14
  • 21
1

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.

df778899
  • 10,703
  • 1
  • 24
  • 36
1

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;

Dan
  • 139
  • 1
  • 6
0

Did you try this? Never tried it myself, but here is the relevant section:

Using the ant javac adapter The Eclipse compiler can be used inside an Ant script using the javac adapter. In order to use the Eclipse compiler, you simply need to define the build.compiler property in your script. Here is a small example.

 <?xml version="1.0" encoding="UTF-8"?>
 <project name="compile" default="main" basedir="../.">

<property name="build.compiler" value="org.eclipse.jdt.core.JDTCompilerAdapter"/>

<property name="root" value="${basedir}/src"/>

<property name="destdir" value="d:/temp/bin" />

<target name="main">
    <javac srcdir="${root}" destdir="${destdir}" debug="on" nowarn="on" extdirs="d:/extdirs" source="1.4">
        <classpath>
          <pathelement location="${basedir}/../org.eclipse.jdt.core/bin"/>
        </classpath>
    </javac>        
</target>
</project>

I would really consider making your classes standards compatible. I believe the official limit is 65535, and the fact that Eclipse is more lenient is something that could change on you at the most inconvenient of times, and either way constantly having to get the project compiled with Eclipse can really start to limit you in too many ways.

Yishai
  • 90,445
  • 31
  • 189
  • 263
0

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

xevser
  • 369
  • 4
  • 5
0

permanent solution would be for this is getting long string from file specially when you are writing test case in spring projects. the below one worked for me

File resource = new ClassPathResource(
      "data/employees.dat").getFile();
    String employees = new String(
      Files.readAllBytes(resource.toPath()));
-4

You can try this,

public static final String CONSTANT = new StringBuilder("Your really long string").toString();
  • This would have same problem of a string constant that is too long. – Nicko Aug 21 '18 at 07:36
  • This would also work, bu not with a long single String. If you cut the String in parts it will work. public static final String CONSTANT = new StringBuilder("Not so long string").append("another not so long string").append("another string").toString(); – gfjr Nov 26 '19 at 13:13