Java Can';在重复追加到字符串上时,不要添加换行符
我正在尝试以特定格式写入文本文档。这是我现在拥有的Java Can';在重复追加到字符串上时,不要添加换行符,java,multithreading,io,Java,Multithreading,Io,我正在尝试以特定格式写入文本文档。这是我现在拥有的 String line = ""; double totalCost = 0; Node curr = summary.head.next; while(curr!=summary.tail) { line += [an assortment of strings and variables] +"\r"; totalCost += PRICELIST.get(curr.
String line = "";
double totalCost = 0;
Node curr = summary.head.next;
while(curr!=summary.tail)
{
line += [an assortment of strings and variables] +"\r";
totalCost += PRICELIST.get(curr.itemName)*curr.count;
curr = curr.next;
}
write.printf("%s" + "%n", line);
这就是添加到生产线上的零件的实际外观
"Item's name: " + curr.itemName + ", Cost per item: " + NumberFormat.getCurrencyInstance().format(PRICELIST.get(curr.itemName)) +
", Quantity: " + curr.count + ", Cost: " + NumberFormat.getCurrencyInstance().format(PRICELIST.get(curr.itemName)*curr.count) + "\r";
我也试过用一个换行符。在我让它工作之前,当print语句在循环中时,这意味着它一次只写一行。我想这样做,因为我将有多个线程写入此文件,这样任何线程都不会持有锁那么长时间。使用System.getProperty(“line.separator”)而不是“\r”
缓存ir以提高效率。您也可以尝试结合使用
\n\r
。这对我的一个项目很有帮助。如果使用Java 7或更高版本,您可以使用首先不要使用
while(..){
result += newString
..
}
内环。这是非常低效的,尤其是对于长文本,因为每次你打电话
result += newString
您正在创建新字符串,该字符串需要复制result
的内容并附加到newStrint
。因此,到目前为止,您处理的文本越多,需要复制的文本就越多,因此速度就越慢
改用
StringBuilder sb = new StringBuilder();
while(..){
sb.append(newString);
}
result = sb.toString.
在你的情况下,哪个应该更像
sb.append("Item's name: ").append(curr.itemName)
.append(", Cost per item: ").append(NumberFormat.getCurrencyInstance().format(PRICELIST.get(curr.itemName)))
.append(", Quantity: ").append(curr.count )
.append(", Cost: ").append(NumberFormat.getCurrencyInstance().format(PRICELIST.get(curr.itemName) * curr.count))
.append(System.lineSeparator());
也代替
write.printf("%s" + "%n", line);
您应该使用更简单的版本,即
write.println(line);
自动添加基于操作系统的行分隔符。这不起作用。最后的结果是在应该有“\n”的地方打印了“null”。可能您键入了“line.separator”错误?System.lineSeparator()适用于您,它返回系统属性line.separator的初始值;根据System.lineSeparator()的文档。为什么要使用
printf
而不是println
?我看了一本关于如何写入文件的教程,它说我必须使用printf。我认为printf就是被使用的东西。您可以将println与filewriter/printwriter一起使用吗?是的,您应该能够在printwriter(可以包装filewriter)上使用它而不会出现问题。是的!谢谢。你知道为什么我在使用filewriter/printwriter时不能使用转义字符吗?谢谢。等我的其他东西好了,我会把它弄进去的。