Java 将数据以表格格式写入文本文件

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/26229140/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-11 02:02:41  来源:igfitidea点击:

Writing data to text file in table format

javanetbeansfile-iofilewriter

提问by Moko

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

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.

宁愿那样。

采纳答案by MadProgrammer

The \r\nis 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...

\r\n被被评为第二个参数的一部分,因此,它基本上计算所需的空间,就像这样...... 20 - "column 2".length() - " \r\n".length(),但由于第二行没有这一点,它需要较少的空间和外观错位...

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

尝试添加\r\n作为基本格式的一部分,例如...

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...

在我的测试中...

回答by Jon Skeet

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\nto be part of the count of 20 characters.

您当前包含" \r\n"在右对齐的第二个参数中。我怀疑您根本不想要空格,并且您不希望 成为\r\n20 个字符计数的一部分。

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

要左对齐而不是右对齐,请使用-标志,即%-20s代替%20s。有关Formatter更多信息,请参阅文档文档。

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

此外,您可以使用%n代表当前平台的行终止符使代码以更跨平台的方式工作(除非您特别想要一个 Windows 文件。

I'd recommend the use of Files.newBufferedWriteras 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:

我也建议使用Files.newBufferedWriter,因为它允许您指定字符编码(否则将使用 UTF-8,这比使用平台默认值更好)......并使用 try-with-resources 语句来即使遇到异常也要关闭作者:

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

回答by CLOUGH

I think you are trying to get data in tabular format. I've developed a Java library that can build much complex tables with more customization. You can get the source code here. Following are some of the basic table-views that my library can create. Hope this is useful enough!

我认为您正在尝试以表格格式获取数据。我开发了一个 Java 库,它可以通过更多的自定义来构建非常复杂的表。您可以在此处获取源代码。以下是我的库可以创建的一些基本表视图。希望这足够有用!

COLUMN WISE GRID(DEFAULT)

列智能网格(默认)

+--------------+--------------+--------------+--------------+-------------+
|NAME          |GENDER        |MARRIED       |           AGE|    SALARY($)|
+--------------+--------------+--------------+--------------+-------------+
|Eddy          |Male          |No            |            23|      1200.27|
|Libby         |Male          |No            |            17|       800.50|
|Rea           |Female        |No            |            30|     10000.00|
|Deandre       |Female        |No            |            19|     18000.50|
|Alice         |Male          |Yes           |            29|       580.40|
|Alyse         |Female        |No            |            26|      7000.89|
|Venessa       |Female        |No            |            22|    100700.50|
+--------------+--------------+--------------+--------------+-------------+

FULL GRID

全格

+------------------------+-------------+------+-------------+-------------+
|NAME                    |GENDER       |MARRIE|          AGE|    SALARY($)|
+------------------------+-------------+------+-------------+-------------+
|Eddy                    |Male         |No    |           23|      1200.27|
+------------------------+-------------+------+-------------+-------------+
|Libby                   |Male         |No    |           17|       800.50|
+------------------------+-------------+------+-------------+-------------+
|Rea                     |Female       |No    |           30|     10000.00|
+------------------------+-------------+------+-------------+-------------+
|Deandre                 |Female       |No    |           19|     18000.50|
+------------------------+-------------+------+-------------+-------------+
|Alice                   |Male         |Yes   |           29|       580.40|
+------------------------+-------------+------+-------------+-------------+
|Alyse                   |Female       |No    |           26|      7000.89|
+------------------------+-------------+------+-------------+-------------+
|Venessa                 |Female       |No    |           22|    100700.50|
+------------------------+-------------+------+-------------+-------------+

NO GRID

无网格

NAME                    GENDER       MARRIE          AGE    SALARY($)      
Alice                   Male         Yes              29       580.40      
Alyse                   Female       No               26      7000.89      
Eddy                    Male         No               23      1200.27      
Rea                     Female       No               30     10000.00      
Deandre                 Female       No               19     18000.50      
Venessa                 Female       No               22    100700.50      
Libby                   Male         No               17       800.50      
Eddy                    Male         No               23      1200.27      
Libby                   Male         No               17       800.50      
Rea                     Female       No               30     10000.00      
Deandre                 Female       No               19     18000.50      
Alice                   Male         Yes              29       580.40      
Alyse                   Female       No               26      7000.89      
Venessa                 Female       No               22    100700.50      

回答by Pedro Fernandes

try {
    PrintWriter outputStream = new PrintWriter("myObjects.txt");
    outputStream.println(String.format("%-20s %-20s %-20s", "Name", "Age", "Gender"));
    outputStream.println(String.format("%-20s %-20s %-20s", "John", "30", "Male"));
    outputStream.close();
} catch (IOException e) {
    e.printStackTrace();
}