Search code examples
javajava-iofile-writing

Why is FileNotFoundException popping up?


I am trying to print Ben, Adam, John and Smith into a txt file with the names on separate lines. I am partly successful, however I keep getting FileNotFoundException at the end after the code runs. Why is that?

"Ben Adam John Smith" passes through String names

File Writing code:

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;
   }

Test file for FileWriting:

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

Code that the error points to:

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;
}

Test file for FileReading:

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

Solution

  • You are trying to read a file where the filename consists of a name or names here:

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

    as writeYourName doesn't return a file name but a string of names of persons (or in this case, one name, of one person: Fred):

    return names;