0

I am simply trying to make a very basic java program to read a file. However I get the error that it can't find my file: Exception in thread "main" java.io.FileNotFoundException: read.txt (The system cannot find the file specified) I checked and I have not misspelled my file name, and the file is already in the same file directory as the program. Here is the code:

import java.io.*;
import java.util.*;

public class save_files {
    public static void main(String[] args) throws FileNotFoundException {

        File file = new File("read.txt");
        Scanner scanner = new Scanner(file);
        String line = scanner.nextLine();
        System.out.println(line);

    }
}
Jacob
  • 41
  • 9

2 Answers2

2

"read.txt" is a relative file path, relative to the 'working dir'. Be sure to specify the path relative to the working dir.

See this answer: How does Java resolve a relative path in new File()?

KevinB
  • 1,102
  • 2
  • 8
  • 19
0

My suggestion is to try the absolute path to the file first. If your code works (which it should), then your problem is the relative path, which also depends on how you're running your code.

If you're using something like NetBeans or Eclipse, your code will work if your file is in the root directory for the project. If your project was named Foo, your directory could look something like this:

Foo
|- build
|- nbproject
|- src
|- test
|- build.xml
|- manifest.mf
|- read.txt

Otherwise, if you're doing something like running a .jar from the command line, the context of "where to find read.txt" will depend on your working directory. If the path is a literal (your case) it will look on the working directory.

atomskaze
  • 101
  • 4