为什么会弹出FileNotFoundException?

我正在尝试将Ben,Adam,John和Smith打印到一个txt文件中,并在各行中分别命名。我取得了部分成功,但是在代码运行之后,我始终在最后获得FileNotFoundException。为什么呢?

“本·亚当·约翰·史密斯”经过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"));
yzmjsk92856 回答:为什么会弹出FileNotFoundException?

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

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

因为writeYourName不会返回文件名,而是返回人员名称的字符串(或在此情况下,一个人的一个名称:Fred):

return names;
本文链接:https://www.f2er.com/2815673.html

大家都在问