Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Writing data to text file in table format

So far I have this:

File dir = new File("C:\\Users\\User\\Desktop\\dir\\dir1\\dir2);
dir.mkdirs();
File file = new File(dir, "filename.txt");
FileWriter archivo = new FileWriter(file);
archivo.write(String.format("%20s %20s", "column 1", "column 2 \r\n"));
archivo.write(String.format("%20s %20s", "data 1", "data 2"));
archivo.flush();
archivo.close();

However. the file output looks like this:

http://i.imgur.com/4gulhvY.png

Which I do not like at all.

How can I make a better table format for the output of a text file?

Would appreciate any assistance.

Thanks in advance!

EDIT: Fixed!

Also, instead of looking like

    column 1             column 2
      data 1               data 2

How can I make it to look like this:

column 1             column 2
data 1               data 2

Would prefer it that way.

like image 612
Moko Avatar asked Dec 05 '22 05:12

Moko


1 Answers

The \r\n is been evaluated as part of the second parameter, so it basically calculating the required space as something like... 20 - "column 2".length() - " \r\n".length(), but since the second line doesn't have this, it takes less space and looks misaligned...

Try adding the \r\n as part of the base format instead, for example...

String.format("%20s %20s \r\n", "column 1", "column 2")

This generates something like...

        column 1             column 2
          data 1               data 2

In my tests...

like image 162
MadProgrammer Avatar answered Dec 06 '22 18:12

MadProgrammer