Search code examples
javaword-wrap

Java Format String for Table Display: Wrap at 80 chars


I need to display a list in table/grid format, so I'm using String.format() as in the following example, how to print object list to file with formatting in table format using java

My issue is that I need to force-wrap the output at 80 chars. The table's maximum width is 80, any further output must continue on the next line.

Is this possible?

Current code, without wrapping implemented:

StringBuilder sbOutput = new StringBuilder();

sbOutput.append(String.format("%-14s%-200s%-13s%-24s%-12s", "F1", "F2", "F3", "F4", "F5"));
for (MyObject result: myObjects) {
    sbOutput.append(String.format("%-14s%-200s%-13s%-24s%-12s", result.getF1(),
      result.getF2(), result.getF3(), result.getF3(), result.getF4()));
}

Solution

  • You can inject a newline into a string every 80 chars like this:

    str.replaceAll(".{80}(?=.)", "$0\n");
    

    So your code would become:

    sbOutput.append(String.format("%-14s%-200s%-13s%-24s%-12s", result.getF1(),
      result.getF2(), result.getF3(), result.getF3(), result.getF4())
        .replaceAll(".{80}(?=.)", "$0\n"));
    

    The search regex means "80 chars that have a character following" and "$0" in the replacement means "everything matched by the search".

    The (?=.) is a look ahead asserting the match is followed by any character, which prevents output that is an exact multiple of 80 chars getting an unecessary newline added after it.