Reputation: 5863
I have a rather silly question, but I haven't been able to find a solution for this:
When I try and read a file I get a "file not found error" is runtime. It compiled the file though.
I am on Linux, so I use the statement something like:
Scanner s = new Scanner(new File("home/me/java/ex.txt"));
and it gives me a runtime rror:
/home/me/javaException in thread "main" java.io.FileNotFoundException: home/me/java/ex.txt (No such file or directory)
at java.io.FileInputStream.open(Native Method)
at java.io.FileInputStream.<init>(FileInputStream.java:137)
at java.util.Scanner.<init>(Scanner.java:653)
at test.main(test.java:14)
I tried changing every possible thing along the lines of filenames, but nothing seems to work.
Any clues as to why this is happening? where does java look for files by default?
Upvotes: 17
Views: 138178
Reputation: 12883
I think Todd is correct, but I think there's one other thing you should consider. You can reliably get the home directory from the JVM at runtime, and then you can create files objects relative to that location. It's not that much more trouble, and it's something you'll appreciate if you ever move to another computer or operating system.
File homedir = new File(System.getProperty("user.home"));
File fileToRead = new File(homedir, "java/ex.txt");
Upvotes: 14
Reputation: 5867
The Official Documentation is clear about Path
.
Linux Syntax: /home/joe/foo
Windows Syntax: C:\home\joe\foo
Note: joe
is your username for these examples.
Upvotes: 3
Reputation: 13521
Looks like you are missing a leading slash. Perhaps try:
Scanner s = new Scanner(new File("/home/me/java/ex.txt"));
(as to where it looks for files by default, it is where the JVM is run from for relative paths like the one you have in your question)
Upvotes: 23