How to print a list of objects to a file with formatting in a table format using java

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

Name       Age      Address

Abc        20       some address1
Def        30       some address2 

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

I'm just wondering if these APIs or tools to work with this formatting?

+5
source share
2 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        
+7
source

Use printf with filled fields to achieve column alignment.

PrintWriter.printf will be specific

0
source

All Articles