How to correctly create tab delimited text file in Java

I am trying to create a tab delimited text file so that the output appears as columns, but for some reason the tab appears in different places. This is because data values โ€‹โ€‹have different sizes.

this is how i build rows and columns

output.append("|\t" + column1 + "\t\t\t:\t" + column2 +" \t\t\n"); 

And the way out comes out like

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

As you can see the values โ€‹โ€‹with longer text entries in the first column, the second column moves a little further, although both columns are separated by two tabs. How can I make sure the second column location is on the same row?

thanks

+4
source share
4 answers

see How can I put a string in Java? for some code additions and place the contents of the column to some arbitrary length.

+3
source

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

+5
source

You will need to set the line length to say 25 characters, and apply the difference x = (25 - column1.length) to x the number of spaces. Remember to use the monophonic font in a text editor.

To lay a line, 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"); 
+3
source

This has nothing to do with whether the file is โ€œcorrectโ€ or not, and all this is related to the display of 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 the GUI is displayed in JTable.

+1
source

Source: https://habr.com/ru/post/1335655/


All Articles