17

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?

2
  • 1
    it says your file location was not found. i guess your path is "/home/me/java/ex.txt" in linux system. Commented Dec 25, 2011 at 2:39
  • What is the value of user.home on that system? Commented Dec 25, 2011 at 2:42

3 Answers 3

23

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)

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks Todd. It was the leading slash.That solved the problem! Silly me!
14

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");

3 Comments

If porting to any other operating system, I suggest swapping out the "/" in the path for either System.getProperty("file.separator") or alternately constructing the path in parts using that constructor. Otherwise, +1
Thanks bill for that great tip. I will implement this straightaway.
If you're targeting unix, linux, OS X, or windows, the forward slash will work. Yes, even Windows.
3

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.