FileInputStream doesn't work with the relative path

Mahmoud Elshamy picture Mahmoud Elshamy · Jan 27, 2013 · Viewed 97.7k times · Source

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

Answer

Bernhard Barker picture Bernhard Barker · Jan 28, 2013

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