开发者

How to correctly create a tab delimited text file in Java

开发者 https://www.devze.com 2023-02-05 01:33 出处:网络
I am trying to create a tab delimeted text file so that the output appears like columns but for some reason the tab appears on different locations. This is caused by the fact that the data values are

I am trying to create a tab delimeted text file so that the output appears like columns but for some reason the tab appears on different locations. This is caused by the fact that the data values are different sizes.

here is how i am building the rows and columns

output.app开发者_高级运维end("|\t" + column1 + "\t\t\t:\t" + column2 +"  \t\t\n");

And the output is coming out as

|   activeSessions      : 0         
|   duplicates      : 0         
|   expiredSessions         : 0         
|   rejectedSessions        : 0         
|   sessionMaxAliveTime         : 0         
|   sessionCounter      : 0         

As you can see the values with longer text entries on the first column causes the second column to move slightly further away even though both column are separated by two tabs. How can i ensure that the second column location is on the same line?

Thanks


The width of a tab character isn't defined and depends on what you use to display the text. If you want to align the columns, use spaces instead. You can align with spaces using a printf format of %10s for example.


see How can I pad a String in Java? for some padding code and pad your column content to some arbitrary length.


You will have to set length of the string to lets say 25 characters and pad the difference x = (25 - column1.length) with x amount of spaces. Don't forget to use mono space font in your text editor.

To pad the string you can use this:StringUtils.rightPad(String, int)

import org.apache.commons.lang.StringUtils;
output.append("|\t" + StringUtils.rightPad(column1, 25) + "\t\t\t:\t" + StringUtils.rightPad(column2, 15) +"  \t\t\n");


This has nothing to do with whether the file is "correct" or not and all to do with your display of the data which is a separate issue. Consider using printf(...) or String.format(..), or other variants of the Formatter class to format your data for display. Or if a GUI, display in a JTable.

0

精彩评论

暂无评论...
验证码 换一张
取 消