How can I format the data written to a text file to be done in columns?
Asked Answered
P

3

7

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.

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 
Panier answered 7/11, 2011 at 22:27 Comment(0)
K
11

Have a look at the Formatter class, or the String.format(String format, Object... args) method.

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

Kiruna answered 7/11, 2011 at 22:32 Comment(0)
I
3

There are a number of options, but the easiest is to use String.format(). See format string details for more info, but roughly:

String.format("%-20s %-10s ...etc...", aName, aObjRef, ...etc...);
Illiterate answered 7/11, 2011 at 22:32 Comment(2)
Note that this will right-align each column. (Also, %n is a good alternative to System.getProperty("line.separator").)Kiruna
@Kiruna Fixed... although I'd rather see that second column aligned on the ., which is only slightly more work.Illiterate
L
2

You can use the String.format command to do something like:

output.write("%20s %20s %20s %20s%s".format(
  aName, aObjRef, aValue, strDate, note, System.getProperty("line.separator")
);
Lawyer answered 7/11, 2011 at 22:35 Comment(1)
Note that this will right-align each column. (Also, %n is a good alternative to System.getProperty("line.separator").)Kiruna

© 2022 - 2024 — McMap. All rights reserved.