【发布时间】:2017-04-26 09:29:54
【问题描述】:
我在使用输入创建文件时遇到问题,我想在其中写入来自另一个文件的行。当我的代码到达我要创建的文件名时,它不允许我在输入后输入任何内容我要打开的文件的文件名。我认为这与扫描仪无法接收最后一个“\n”或其他什么有关,所以我在第一次调用它后尝试用 sc.nextLine() 来“刷新”它,但它没有不工作。我不太明白系统的逻辑不适用于第二个 nextLine(),它不应该与第一个相同吗?谁能解释一下?
try {
System.out.println("Enter the file name to open with extension: ");
Scanner sc = new Scanner(System.in);
File file = new File(sc.nextLine());
sc = new Scanner(file); //opens inputted file name
// System.err.println(file.getAbsolutePath());
System.out.println("What is the file name you want to create? ");
// sc.nextLine();
File write = new File(sc.nextLine());
PrintWriter writer = new PrintWriter(write);
// System.out.println("Copying file contents over... ");
while (sc.hasNextLine()) {
String line = sc.nextLine();
writer.println(line);
}
writer.close();
sc.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
}
【问题讨论】:
标签: java input file-io output java.util.scanner