【问题标题】:Java: Skipping the first line of user input when appending a text file?Java:附加文本文件时跳过用户输入的第一行?
【发布时间】:2016-02-09 20:55:32
【问题描述】:

所以我试图接受来自用户的文本行,以便将其附加到 txt 文件中。但是,程序运行后,用户输入的第一行不会出现在附加文件中。

下面是部分代码:

System.out.println("enter advice (hit return  on empty line to quit):");
String advice = keyboard.nextLine();

FileWriter fw = new FileWriter(inputFile, true);
PrintWriter pw = new PrintWriter(fw);

for(int n = 1; n <= 2; ++n)
{
  advice = keyboard.nextLine();
  pw.print(advice);
}

pw.close();
keyboard.close();

这是代码的示例运行:

$ java Advice
enter input filename: Advice.txt **enter**
1: fully understand the given problem
2: do analysis and design first before typing
enter advice (hit return  on empty line to quit):
a **enter**
b **enter**

Thank you, goodbye!
$ cat Advice.txt
1: fully understand the given problem
2: do analysis and design first before typing
b

有什么想法吗? 谢谢!

【问题讨论】:

  • 但在您的示例中,第一行是以 1 开头的,对吗?那是在文件中,还是不是?
  • 正确,“1:完全理解给定的问题 2:...”已经是 txt 文件的一部分,我想在其中附加用户输入的文本行。

标签: java java.util.scanner filewriter printwriter


【解决方案1】:

用户输入的第一行被捕获,但不被写入文件。 String advice = keyboard.nextLine(); 当您写入文件时,您将接受下一个用户输入

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-03-04
    • 1970-01-01
    • 2017-04-21
    • 1970-01-01
    • 2014-01-31
    • 1970-01-01
    • 2019-09-23
    • 2014-01-26
    相关资源
    最近更新 更多