Java Java file path

I have a pretty dumb question, but I could not find a solution for this:

When I try to read a file, I get the error message "file not found" - this is the runtime. He compiled the file.

I am on Linux, so I use the instruction like this:

Scanner s = new Scanner(new File("home/me/java/ex.txt")); 

and he gives me rror runtime:

 /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 to change all possible things according to the file names, but nothing works.

Any clues as to why this is happening? where is java looking for default files?

+8
java
source share
2 answers

It looks like you are missing a leading slash. Perhaps try:

 Scanner s = new Scanner(new File("/home/me/java/ex.txt")); 

(regarding where it looks for default files, this is where the JVM starts from relative paths, like the one you have in your question)

+14
source share

I think Todd is right, but I think there is one more thing that you should consider. You can reliably get the home directory from the JVM at runtime, and then you can create file objects relative to this location. This is not much more of a problem, and it is something that you will enjoy if you ever switch to another computer or operating system.

 File homedir = new File(System.getProperty("user.home")); File fileToRead = new File(homedir, "java/ex.txt"); 
+10
source share

All Articles