简体   繁体   English

如何格式化写入文本文件的数据在列中完成?

[英]How can I format the data written to a text file to be done in columns?

Hi I have a bunch of data Im writing to a text file, each line of the rows holds about 4 different pieces of data, I want to make it so that each type is data is aligned in rows. 嗨我有一堆数据我正在写入文本文件,每行的行包含大约4个不同的数据,我想让它成为每个类型的数据在行中对齐。

Here is the line that writes the data. 这是写入数据的行。

output.write(aName + "    "  + aObjRef + "    "  + aValue + "    "  + strDate + "    " + note  + (System.getProperty("line.separator")));

Here is how the data looks when written right now. 以下是现在编写时数据的外观。

CR_2900_IPGR_AL    2900.EV2    Alarm    111107    
CR_2900_IMPT_AL    2900.EV311    Alarm    111107    
CR_STH_CHL_AL    2900.EV315    Alarm    111107    
CR_OAT_AL    2900.EV318    Alarm    111107    
SLB_102_2270A Temp Event    60215.EV1    Fault    111107    
MACF_70300_IMPT_AL    70300.EV2    Alarm    111107 

And here is how Id like it to look 以下是我喜欢它的样子

CR_2900_IPGR_AL             2900.EV2        Alarm      111107    
CR_2900_IMPT_AL             2900.EV311      Alarm      111107    
CR_STH_CHL_AL               2900.EV315      Alarm      111107    
CR_OAT_AL                   2900.EV318      Alarm      111107    
SLB_102_2270A Temp Event    60215.EV1       Fault      111107    
MACF_70300_IMPT_AL          70300.EV2       Alarm      111107 

Have a look at the Formatter class, or the String.format(String format, Object... args) method. 查看Formatter类或String.format(String format, Object... args)方法。

Try this for instance: 试试这个例子:

String formatStr = "%-20s %-15s %-15s %-15s %-15s%n";
output.write(String.format(formatStr, aName, aObjRef, aValue, strDate, note));

(Note that %n will automatically use the platform-specific line separator.) (请注意, %n将自动使用特定于平台的行分隔符。)

There are a number of options, but the easiest is to use String.format() . 有许多选项,但最简单的是使用String.format() See format string details for more info , but roughly: 有关详细信息 ,请参阅格式字符串详细信息

String.format("%-20s %-10s ...etc...", aName, aObjRef, ...etc...);

You can use the String.format command to do something like: 您可以使用String.format命令执行以下操作:

output.write("%20s %20s %20s %20s%s".format(
  aName, aObjRef, aValue, strDate, note, System.getProperty("line.separator")
);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM