4

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.append("|\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

ziggy
  • 14,901
  • 61
  • 181
  • 273

4 Answers4

5

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.

moinudin
  • 117,949
  • 42
  • 185
  • 213
3

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");
MatBanik
  • 24,206
  • 38
  • 107
  • 172
3

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

Community
  • 1
  • 1
1

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.

Hovercraft Full Of Eels
  • 276,051
  • 23
  • 238
  • 346