我无法使用输入来创建我想从另一个文件中写入行的文件。当我的代码到达我要创建的文件名时,它不会让我输入任何内容在我输入要打开的文件的文件名后。我认为这与扫描仪无法接受最后一次" \ 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();
}
答案 0 :(得分:0)
试试这个:
try {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter the file name to open with extension: ");
File file = new File(br.readLine());
Scanner sc = new Scanner(file); //opens inputted file name
System.out.println("What is the file name you want to create? ");
File write = new File(br.readLine());
PrintWriter writer = new PrintWriter(write);
while (sc.hasNextLine()) {
String line = sc.nextLine();
writer.println(line);
}
writer.close();
sc.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}