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?
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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With