jgg
jgg

Reputation: 1136

How to print object list to file with formatting in table format

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?

Upvotes: 5

Views: 8816

Answers (3)

Michał Jaroń
Michał Jaroń

Reputation: 624

Library for printing Java objects as Markdown / CSV / HTML table using reflection: https://github.com/mjfryc/mjaron-etudes-java

dependencies {
    implementation 'io.github.mjfryc:mjaron-etudes-java:0.2.1'
}
import pl.mjaron.etudes;

class Sample {
    void sample() {
        Cat[] cats = {cat0, cat1};
        Table.render(cats, Cat.class)
            .markdown() // or .csv() or .html()
            .to(System.out) // Or to StrigBuilder | OutputStream | File.
            
            // Optionally specify Left /Right / Center alignment.
            .withAlign(VerticalAlign.Left)
            
            .run(); // Or .runToString() to return it to String.
    }
}

Sample Markdown output:

| name | legsCount | lazy  | topSpeed |
|------|-----------|-------|----------|
| John | 4         | true  | 35.24    |
| Bob  | 5         | false | 75.0     |

Upvotes: 0

aioobe
aioobe

Reputation: 421310

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        

Upvotes: 8

Daniel
Daniel

Reputation: 28104

Use printf with padded fields to achive column alignments.

PrintWriter.printf to be specific

Upvotes: 0

Related Questions