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

后端 未结 2 1503
夕颜
夕颜 2021-01-13 02:25

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 shou

相关标签:
2条回答
  • 2021-01-13 02:40
    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        
    
    0 讨论(0)
  • 2021-01-13 02:57

    Use printf with padded fields to achive column alignments.

    PrintWriter.printf to be specific

    0 讨论(0)
提交回复
热议问题