Writing data to text file in table format

后端 未结 4 1622
感动是毒
感动是毒 2020-12-03 19:30

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\");
         


        
4条回答
  •  攒了一身酷
    2020-12-03 20:16

    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")); 
    }
    

提交回复
热议问题