java - 如何让输入的数据进入文本文件的下一行
问题描述
我有一个包含日期、名称、描述和金额的文本文件。
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
我该如何解决?
解决方案
您的文件显然不以换行符结尾。如果要在新行上添加新文本,则需要先打印此换行符,然后再打印文本。
代替:
pw.println(date+", "+expense+", "+description+", "+amount);
和:
pw.print(System.lineSeparator()+date+", "+expense+", "+description+", "+amount);
推荐阅读
- java - 在 Android/iOS 中使用动态行构建表单
- android - 尝试从本地服务器加载数据时,模拟器显示空白屏幕
- c# - Xamarin.Forms 中 TabbedPage 上的 Android.Views.InflateException
- replace - 将优先级列值替换为“是”应为 1,“否”应为 0
- python - 有没有办法在你的主文件中使用另一个 Python 文件中的变量?
- reactjs - 如何在另一个 asyncThunk 中调度 asyncThunk
- gnuplot - Gnuplot pm3d 绘制“inf”值白色
- r - R中的表格采用错误的形式
- python - Img 标签的 src 在爬网执行时发生了变化,因为类延迟加载?
- c++ - 将左值引用返回到修改后的右值参数