2

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!

2

1 Answer 1

7

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.