以表格格式将数据写入文本文件 [英] Writing data to text file in table format
问题描述
到目前为止,我有这个:
$ p $ 文件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\\\
));
archivo.write(String.format(%20s%20s,data 1,data 2));
archivo.flush();
archivo。 close();
然而,文件输出如下所示:
我不喜欢它。
如何为文本文件的输出创建更好的表格格式?
感谢任何帮助。
感谢您!
编辑:修正!
此外,而不是看起来像
co lumn 1 column 2
data 1 data 2
我怎样才能让它看起来像这样:
第1栏第2栏
数据1数据2
宁可这样。
\r\\\
已被作为第二个参数的一部分进行计算,所以它基本上计算所需的空间,如...
20 - 列2.length() - \r\\\
,但由于第二行没有这个,它占用更少的空间,看起来没有对齐... p>
.length()
尝试添加 \r\\\
作为基本格式的一部分,例如... >
String.format(%20s%20s \r\\\
,column 1,column 2)
这会产生类似...
第1列第2列
数据1数据2
在我的测试中...
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:
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.
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...
这篇关于以表格格式将数据写入文本文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!