为什么会弹出 FileNotFoundException?

Why is FileNotFoundException popping up?

我正在尝试将 Ben、Adam、John 和 Smith 打印到一个 txt 文件中,名称在不同的行中。我部分成功了,但是在代码运行后我一直在最后得到 FileNotFoundException。这是为什么?

"Ben Adam John Smith"穿过String names

文件写入代码:

public String writeYourName(String names) throws Exception {
    PrintWriter output = new PrintWriter(new BufferedWriter(new FileWriter("names.txt")));
        for(int i = 0; i < 1; i++) {
            output.write(names);
        }
        output.close();

    Scanner scan1 = new Scanner(new File("names.txt"));
        while(scan1.hasNext()) {
            if(scan1.hasNext()) {
                System.out.println(scan1.next());
            }
        }
        return names;
   }

FileWriting 的测试文件:

FileWriting fileWriting = new FileWriting();
FileReading fileReading = new FileReading();
fileWriting.writeYourName("Ben Adam John Smith");
System.out.println(fileReading.readName1(fileWriting.writeYourName("Fred")));

错误指向的代码:

public class FileReading {

public String readName1(String nameFile) throws Exception {
    -> Scanner scan = new Scanner(new File(nameFile)); <-
    String name = scan.next();
    String nextLine = "";
    while(scan.hasNextLine()) {
        nextLine = scan.nextLine();
    }
    return name + " " + nextLine;
}

FileReading 的测试文件:

System.out.println(fileInput.readName1("namefile.txt"));

您正在尝试读取文件名由一个或多个名称组成的文件:

fileReading.readName1(fileWriting.writeYourName("Fred"))

因为 writeYourName 不是 return 文件名,而是一串人名(或者在这种情况下,一个人的名字:Fred):

return names;