BillMan BillMan - 1 year ago 93
Java Question

How to indent a multi-line paragraph being written to the console in java

Can anyone suggest a method for writing a mutli-line String to a system console and having that text block be indented? I'm looking for something relatively lightweight because it's only being used for displaying help for a command line program.

Mac Mac
Answer Source

NOTE: The approach described below does not meet the updated requirements described by @BillMan in the question's comments. This will not automatically wrap lines that are longer than the console line length - only use this approach if wrapping isn't an issue.

As a simple option, you could use String.replaceAll() as follows:

String output = <your string here>
String indented = output.replaceAll("(?m)^", "\t");

If you're unfamiliar with Java regular expressions, it works as follows:

  • (?m) enables multiline mode. This means each line in output is considered individually, instead of treating output as a single line (which is the default).
  • ^ is a regex matching the start of each line.
  • \t causes each match of the preceding regex (i.e. the start of each line) to be replaced by a tab character.

As an example, the following code:

String output = "foo\nbar\nbaz\n"
String indented = output.replaceAll("(?m)^", "\t");

Produces this output:

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download