在保存的txt文件中排列文本

时间:2013-06-12 22:59:47

标签: java android

我创建了一个带有一些值的应用程序并将它们添加到txt文件中。 它做的是这样的,它们是字符串[]:

product[1]  quantity[1]  price[1]
product[2]  quantity[2]  price[2]
.....
product[n]  quantity[n]  price[n]

问题在于,产品[1]大多数时间不会与产品[2]或其他产品具有相同的长度,而且数量和价格也相同。这导致文本布局混乱,像这样的东西。

ww    2    4
wwww    1    2.5
w    1.2    1.1

有什么方法可以让它更整洁吗?像创建一个或多个表的东西? 谢谢!

编辑:为了让它更清晰一点,我想找到一种方法,让txt文件中的东西像这样排列,而不是在上面的例子中如何

ww      2      4
wwww    1      2.5
w       1.2    1.1

目前我正在使用它      pw.println(prod [n] +"" + cant [n] +"" + pret [n]);} 但这使得txt文件中的文本不对齐(例1)

1 个答案:

答案 0 :(得分:3)

使用format类的String方法,如下所示: 声明格式为

的String
String yourFormat = "%-10s %-10s %-10s%n"; //choose optimal ranges. 
//if you exceed them, it will always automatically make one space 
//between the next column

使用该格式编写输出:

output.write(String.format(yourFormat, firstString, secondString, thirdString));

第一个字符串是你的w,第二个和第三个是带数字的列。

为您的例子:

String myFormat = "%-10s %-10s %-10s%n";
for(int i=0;i<prod.length();i++){
   pw.println(String.format(myFormat, prod[n], cant[n], pret[n]));
}

更多信息herehere

相关问题