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

Bee*_*eef 6 java text-files bufferedwriter

嗨我有一堆数据我正在写入文本文件,每行的行包含大约4个不同的数据,我想这样做,以便每个类型的数据在行中对齐.

这是写入数据的行.

output.write(aName + "    "  + aObjRef + "    "  + aValue + "    "  + strDate + "    " + note  + (System.getProperty("line.separator")));
Run Code Online (Sandbox Code Playgroud)

以下是现在编写时数据的外观.

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 
Run Code Online (Sandbox Code Playgroud)

以下是我喜欢它的样子

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 
Run Code Online (Sandbox Code Playgroud)

aio*_*obe 9

看看Formatter课程或String.format(String format, Object... args)方法.

试试这个例子:

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

(注意,%n将自动使用特定于平台的行分隔符.)