KRB
KRB

Reputation: 5185

Java output to file in table format?

I have a bunch of info that I want to output to a file and it needs to be setup like a table. For example, I need columns with titles and information below each column.

I have four items being printed at a time that each need their own row. A %n before the next.

Should I use system.out.format? Should I be appending data to a file with the PrintStream class?

I would like to stick with Java's basic utilities and classes.

I want my output to look like this...

*Title1*  *Title2*  *Title3*  *Title4*  *Title5*
 info1     info1     info1     info1     info1
 info2     info2     info2     info2     info2
....3

Thanks for any help!

Upvotes: 2

Views: 22788

Answers (1)

Alex K
Alex K

Reputation: 22867

You can use code like this:

Formatter fmt = new Formatter(); 

System.out.println(fmt.format("%s %s %s %s %s", "Title*", "Title*", "Title*", "Title*", "Title*"));

See Formatter java doc

Sample code which prints table which has 20 characters column width:

    Formatter formatter = new Formatter();
    System.out.println(formatter.format("%20s %20s %20s %20s %20s", "Title*", "Title*", "Title*", "Title*", "Title*"));

    for (int i = 0; i < 10; i++) {
        formatter = new Formatter();
        String rowData = "info" + i;
        System.out.println(formatter.format("%20s %20s %20s %20s %20s", rowData, rowData, rowData, rowData, rowData));
    }

For writing data to file you can use java.io package

Upvotes: 7

Related Questions