1

In Java I am using a large String for <Html> codes which meant to create a complete designed email body. eg.

String msg= 
            "<html>"+
            <BODY CONTENT>
             "</html>";

Problem is I am getting error "constant string too long”. I need some ideas if anyone of you have solved this issue or faced this.

Crime_Master_GoGo
  • 1,641
  • 1
  • 20
  • 30

3 Answers3

2

There is limitation the Constant string but one can have a much larger String in memory as long as it is created at run-time such as by reading it through a resource.

You can try this solution.

private static String msg = null;

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

You can call it and save it in another string :

String str = getMyString();
System.out.println("str = " + str);

or you can build your string with the string builder.

StringBuilder sb = new StringBuilder(100);
sb.append("<html>")
      .append("<body>").append(bodycontent)
      .append("</body>")
      .append("</html>");
String result = sb.toString();

Hope this is helpful. cheers

Anuj.T
  • 1,598
  • 16
  • 31
2

There is not so many things we can do when facing constant string too long error.

Constants are constrained to 64K elements per single String entry, but you can split your exceeding constant in a couple of smaller than 64K ones as a workaround.

In terms of software design, at the other hand, the idea of working with complete email bodies as just Strings is not ultimately perfect. Usually developers are using template engines for such purposes and do externalize email bodies to a separate files rather than String constants. Please see Chunk template engine as example which fits well into Android app, but there are lots of another such as Velocity or Freemarker. Template engine lets you clearly separate static email content from dynamically-populated pieces, separate your application data model from it's html representation, and maintain valid architecture of your software

Being not aware of exact reason which prevents you from making a file instead of constant, there are lots of best practices to solve typical file-connected issues starting from embedding files into your jar as resources and ending in encrypting them to avoid unwanted leakage. Just ask another question on SO here.

Kostiantyn
  • 1,856
  • 11
  • 13
1

Try to use StringBuilder, e.g.:

StringBuilder msg = new StringBuilder(here_put_size); //change string size, default value is 16 characters
msg.append("<html>");
msg.append("<BODY CONTENT>");
msg.append("</html>");
return msg.toString();