views:

614

answers:

3

I'm getting results from a database and want to output the data as a table in Java's standard output

I've tried using \t but the first column I want is very variable in length.

Is there a way to display this in a nice table like output?

A: 

Check out the class java.util.Formatter.

PartlyCloudy
+3  A: 

Use System.out.format . You can set lengths of fields like this:

System.out.format("%32s%10d%16s", string1, int1, string2);

This pads string1, int1, and string2 to 32, 10, and 16 characters, respectively.

See the Javadocs for java.util.Formatter for more information on the syntax (System.out.format uses a Formatter internally).

Michael Myers
Thanks just what I needed! I'll just add I needed to put \n at the end to produce a new line each time, in case anyone else finds that problem.
Chris
Or, better, a `%n` -- it gets automatically translated into the system's default line terminator.
Michael Myers
A: 

In short - No, because you have no knowledge of the tab size or even whether the console is using a fixed width font.

However, assuming it is using a fixed width font, it should be fairly straightforward to pad each cell value with spaces to ensure that all cells in a given column are the same width.

Adamski