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

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

本文介绍了以表格格式将数据写入文本文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

到目前为止,我有这个:

$ p $ p>

尝试添加 >

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

这篇关于以表格格式将数据写入文本文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-20 09:50