Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

FileInputStream doesn't work with the relative path [closed]

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 !"); } 
like image 754
Mahmoud Elshamy Avatar asked Jan 27 '13 22:01

Mahmoud Elshamy


People also ask

Does FileInputStream need to be closed?

Yes, you need to close the inputstream if you want your system resources released back. FileInputStream. close() is what you need.

Which exception is thrown by FileInputStream?

The FileInputStream read() method throws a java. io. IOException if for some reason it can't read from the file. Again, the InputFile class makes no attempt to catch or declare this exception.

What is the difference between FileReader and FileInputStream?

FileInputStream is Byte Based, it can be used to read bytes. FileReader is Character Based, it can be used to read characters. FileInputStream is used for reading binary files. FileReader is used for reading text files in platform default encoding.


Video Answer


1 Answers

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")); 
like image 56
Bernhard Barker Avatar answered Sep 28 '22 04:09

Bernhard Barker