【发布时间】:2018-11-24 14:44:06
【问题描述】:
我有一个包含日期、名称、描述和金额的文本文件。
10/10/2018, Gel, Hair Product, 2000.00
使用我制作的代码,用户可以在原始文本文件中输入一个新行:
public static void recordExpense(String filename)throws IOException{
String expense = "";
String date = "";
String description = "";
double amount = 0.0;
PrintWriter pw = null;
try {
pw = new PrintWriter(new BufferedWriter(new FileWriter(filename,true)));
date = readDate(); //user enters the date
expense = readExpense(); //user enters the name of the expense
description = readDescription(); // user enters the description of the expense
amount = readAmount(); .//user enters how much it costs
pw.println(date+", "+expense+", "+description+", "+amount);
pw.close();
}catch (Exception e){
System.out.println("The file could not be found");
}
}
而不是像预期的输出:
10/10/2018, Gel, Hair Product, 2000.00
11/10/2018, Comb, Stuff, 20.00
它会变成这样:
10/10/2018, Gel, Hair Product, 2000.0011/10/2018, Comb, Stuff, 20.00
我该如何解决这个问题?
【问题讨论】:
-
所以你想让它像第二个例子一样出来,所有的都在一条直线上?
-
没有他想要的第一
-
不,我需要它作为第一个示例。
-
您的程序正在运行,
println()似乎无法创建新行,请尝试print()。创建一个常量private static final String newline = System.getProperty("line.separator");并使用pw.print(date+", "+expense+", "+description+", "+amount+newLine);。 -
如果文件已经存在,并且您不能触摸它,您必须先阅读它以检查它是否在末尾包含一个空行。然后根据需要先添加缺少的空行。