如何在 Java 中正确创建制表符分隔的文本文件
我正在尝试创建一个制表符分隔的文本文件,以便输出看起来像列,但由于某种原因,选项卡出现在不同的位置。这是由于数据值大小不同造成的。
这是我构建行和列的方式
output.append("|\t" + column1 + "\t\t\t:\t" + column2 +" \t\t\n");
,输出如下所示,正如
| activeSessions : 0
| duplicates : 0
| expiredSessions : 0
| rejectedSessions : 0
| sessionMaxAliveTime : 0
| sessionCounter : 0
您所看到的,第一列上具有较长文本条目的值会导致第二列稍微移得更远,即使两列都由两个选项卡分隔。如何确保第二列位置位于同一行?
谢谢
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
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
制表符的宽度未定义,取决于您用来显示文本的内容。如果要对齐列,请使用空格。您可以使用
printf
格式与空格对齐例如%10s
。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.请参阅 如何在 Java 中填充字符串? 了解一些填充代码并将列内容填充到一些任意的长度。
see How can I pad a String in Java? for some padding code and pad your column content to some arbitrary length.
您必须将字符串的长度设置为 25 个字符,并用 x 个空格填充差值
x = (25 - column1.length)
。不要忘记在文本编辑器中使用单空格字体。要填充字符串,您可以使用以下命令:StringUtils.rightPad(String, int)
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)
这与文件是否“正确”无关,而与数据的显示有关,这是一个单独的问题。考虑使用 printf(...) 或 String.format(..) 或 Formatter 类的其他变体来格式化数据以供显示。或者如果是 GUI,则显示在 JTable 中。
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.