Reputation: 1847
I've been scouring the web for a solution to this seemingly simple problem, but I always run into FileNotFoundException
. I am using Java 8 on Eclipse Oxygen and can't retrieve my txt
file from either absolute path or relative path. As suggested in other SO answers I got the path to the current directory, which I suppose is where the txt file is loaded from:
Path path = FileSystems.getDefault().getPath("").toAbsolutePath();
This showed my directory as E:\eclipse-java-oxygen-R-win32\HashMap
However, when I added my txt file to that project directory (containing src
,bin
directories) it still couldn't find the file when I wrote: Scanner input = new Scanner(new File("free.txt"))
I even tried the absolute path: Scanner input = new Scanner(new File("E://eclipse-java-oxygen-R-win32//HashMap//free.txt"));
I included a screenshot of the location of my free.txt file below.
Your help would be much appreciated.
Upvotes: 0
Views: 363
Reputation: 1838
Hmm, lets try to split things up so that we know what exactly is the problem. You could also try to get a more explicit error message by printing the exact error of the File Exception. Something like this:
catch (IOException e) {
System.out.println("IOException caught -- ");
System.out.println(e.getMessage());
}
But going further. Your line: Scanner input = new Scanner(new File("free.txt"))
can be split up.
Try this:
String file_name="free.txt";
File file_input = new File(file_name);
if (!file_input.exists())
abort("FileInput: no such source file: " + file_name);
if (!_file_input.isFile())
abort("FileInput: can't open a directory: " + file_name);
if (!file_input.canRead())
abort("FileInput: source file is unreadable: " + file_name);
Then run
try {
`Scanner input = new Scanner(file_input)`
catch (FileNotFoundException e) {
e.printStackTrace();
}
At least this should tell you more about the error and do the debugging for you.
Upvotes: 1
Reputation:
I don't know where your file is but I think this is what you're looking for. i have a file named test.json
String jsonString = new String(Files.readAllBytes(Paths.get(ClassLoader.getSystemResource("test.json").toURI())));
Upvotes: 0