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.

Jon Skeet
people
quotationmark

You're currently including " \r\n" within your right-aligned second argument. I suspect you don't want the space at all, and you don't want the \r\n to be part of the count of 20 characters.

To left-align instead of right-aligning, use the - flag, i.e. %-20s instead of %20s. See the documentation for Formatter documentation for more information.

Additionally, you can make the code work in a more cross-platform way using %n to represent the current platform's line terminator (unless you specifically want a Windows file.

I'd recommend the use of Files.newBufferedWriter as well, as that allows you to specify the character encoding (and will use UTF-8 otherwise, which is better than using the platform default)... and use a try-with-resources statement to close the writer even in the face of an exception:

try (Writer writer = Files.newBufferedWriter(file.toPath())) {
  writer.write(String.format("%-20s %-20s%n", "column 1", "column 2"));
  writer.write(String.format("%-20s %-20s%n", "data 1", "data 2")); 
}

people

See more on this question at Stackoverflow