首页 > 解决方案 > 如何让输入的数据进入文本文件的下一行

问题描述

我有一个包含日期、名称、描述和金额的文本文件。

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

我该如何解决?

标签: javatext

解决方案


您的文件显然不以换行符结尾。如果要在新行上添加新文本,则需要先打印此换行符,然后再打印文本。

代替:

pw.println(date+", "+expense+", "+description+", "+amount);

和:

pw.print(System.lineSeparator()+date+", "+expense+", "+description+", "+amount);

推荐阅读