How to format tabular data as text in Java?

I would like to create beautifully formatted tabular text from arbitrary models of dataset objects. Is there a good library for this in Java?

In particular, I need output that is formatted as command line data management tools such as the CLI for mysql. Example:

+---------+--------------+------+-----+---------+-------+ | Field | Type | Null | Key | Default | Extra | +---------+--------------+------+-----+---------+-------+ | name | varchar(100) | YES | | NULL | | | release | year(4) | YES | | NULL | | | studio | varchar(50) | YES | | NULL | | | review | varchar(50) | YES | | NULL | | | gross | int(11) | YES | | NULL | | +---------+--------------+------+-----+---------+-------+ 

One of the main problems is that I will not automatically know the maximum column widths before I start crawling the data. In addition, there are many edge cases, such as handling very large lengths of values ​​and a large number of rows and columns.

If I need to build this on my own, I assume that I will use String.format, and I will need to pre-analyze the complete data set before starting the output. This is a very low level of coding, so I would like to find a good library that has already solved this problem.

+6
java formatting text
source share
3 answers

Check out TableFormatter : it does what you want to format the table data. Source code is also available. You can add rows and cells to the table using a convenient interface. The following is an example:

 TableFormatter tf = new SimpleTableFormatter(true) // true = show border .nextRow() .nextCell() .addLine("Field") .nextCell() .addLine("Type") 

Thus, it will create cells in the correct format and adjust the spaces accordingly. It will also allow you to do basic text alignment inside the cell (center, top, bottom)

+7
source share

trac.inamik.com/trac/jtable_format is under the GPL, in some cases this is not suitable.

Another option (Apache 2 license):

http://sourceforge.net/projects/texttablefmt/

+3
source share

For those of interest, I have a forked TableFormatter (which is a dual GPL and MIT license) to make it universal and remove the entire warning compilation.

Please note that I am using the Java 7 diamond operator, so for it to be compatible with Java 6, you will need to add types in list declarations.

+1
source share

All Articles