30

I tried to create an object from FileInputStream and pass the relative value of a file to its constructor, but it doesn't work properly and threw a FileNotFoundException

try {
   InputStream is = new FileInputStream("/files/somefile.txt");
} catch (FileNotFoundException ex) {
   System.out.println("File not found !");
}
3
  • 2
    /files is not a relative path. Do you mean ./files?
    – John3136
    Jan 27, 2013 at 22:57
  • 2
    That's not a relative path. It's an absolute path.
    – JB Nizet
    Jan 27, 2013 at 22:58
  • Either "./files/" or "files/" should work as a relative path.
    – djangofan
    Jan 27, 2013 at 23:05

3 Answers 3

62

The / at the start will make the path absolute instead of relative.

Try removing the leading /, so replace:

InputStream is = new FileInputStream("/files/somefile.txt");

with:

InputStream is = new FileInputStream("files/somefile.txt");

If you're still having trouble, try making sure the program is running from where you think by checking the current directory:

System.out.println(System.getProperty("user.dir"));
2
  • i found same error but with russian filename only what sould i do. My file path /storage/emulated/0/fourth_ррссттууффххцц.txt pls help Feb 11, 2014 at 6:10
  • 2
    No, doesn't work if the file is in the same directory as the InputStream instance code. Mar 22, 2016 at 20:28
8

The other posters are right the path you are giving is not a relative path. You could potentially do something like this.getClass().getResourceAsStream("Path relative to the current class"). This would allow you to load a file as a stream based on a path relative to the class from which you call it.

See the Java API for more details: http://docs.oracle.com/javase/7/docs/api/java/lang/Class.html#getResourceAsStream(java.lang.String)

5
  1. this is not a relative path, it is an absolute path.
  2. If you are on Windows you need to add your drive letter before your path:

InputStream is = new FileInputStream("C:/files/somefile.txt");

windows doesn't support the / symbol as "root"

If you want to load a file thatt you'll put in your JAR, you need to use

getClass().getResource("path to your file");

or

getClass().getResourceAsStream("path to your file");
3
  • 1
    files is a package in the src folder of the project , and I want to make this folder or package part of the final .jar file Jan 27, 2013 at 22:59
  • ok, but your path is not relative, so you need to use a relative path OR specify the absolute path for your file
    – BackSlash
    Jan 27, 2013 at 23:01
  • okay , could you give me a code to get the absolute path of the final .jar file :) Jan 27, 2013 at 23:03

Not the answer you're looking for? Browse other questions tagged or ask your own question.