Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to print object list to file with formatting in table format using java

Tags:

java

I have to print list of objects to a text file with table format. For example, if I have list of Person(has getName,getAge and getAddress methods)objects, the text file should look like as below.

Name       Age      Address

Abc        20       some address1
Def        30       some address2 

I can do this by manually writing some code, where I have to take care of spaces and formatting issues.

I am just curious whether are they APIs or tools to do this formatting work?

like image 459
jgg Avatar asked May 10 '10 18:05

jgg


People also ask

Can you print objects in Java?

The print(Object) method of PrintStream Class in Java is used to print the specified Object on the stream. This Object is taken as a parameter. Parameters: This method accepts a mandatory parameter object which is the Object to be printed in the Stream. Return Value: This method do not returns any value.

How do I create a table contents file?

Select the text that you want to convert, and then click Insert > Table > Convert Text to Table. In the Convert Text to Table box, choose the options you want. Under Table size, make sure the numbers match the numbers of columns and rows you want.


1 Answers

import java.util.*;

public class Test {

    public static void main(String[] args) {
        List<Person> list = new ArrayList<Person>();
        list.add(new Person("alpha", "astreet", 12));
        list.add(new Person("bravo", "bstreet", 23));
        list.add(new Person("charlie", "cstreet", 34));
        list.add(new Person("delta", "dstreet", 45));

        System.out.println(String.format("%-10s%-10s%-10s", "Name", "Age", "Adress"));
        for (Person p : list)
            System.out.println(String.format("%-10s%-10s%-10d", p.name, p.addr, p.age));
    }
}

class Person {
    String name;
    String addr;
    int age;
    public Person(String name, String addr, int age) {
        this.name = name;
        this.addr = addr;
        this.age = age;
    }
}

Output:

Name      Age       Adress    
alpha     astreet   12        
bravo     bstreet   23        
charlie   cstreet   34        
delta     dstreet   45        
like image 149
aioobe Avatar answered Sep 18 '22 15:09

aioobe