【问题标题】:How do I have the entered data go into the next line of a text file如何让输入的数据进入文本文件的下一行
【发布时间】: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);
  • 如果文件已经存在,并且您不能触摸它,您必须先阅读它以检查它是否在末尾包含一个空行。然后根据需要先添加缺少的空行。

标签: java text


【解决方案1】:

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

替换:

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

与:

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

【讨论】:

  • 这将在文件中添加空行。有时使用行分隔符也很奇怪,有时使用\n。
  • @JBNizet 我的错误,已修复。
猜你喜欢
  • 2011-11-09
  • 2013-10-18
  • 2019-03-07
  • 2011-09-09
  • 1970-01-01
  • 1970-01-01
  • 2018-02-24
  • 1970-01-01
  • 2019-09-12
相关资源
最近更新 更多