Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get FileNotFoundException when initialising FileInputStream with File object

I am trying to initialise a FileInputStream object using a File object. I am getting a FileNotFound error on the line

fis = new FileInputStream(file);

This is strange since I have opened this file through the same method to do regex many times.

My method is as follows:

private BufferedInputStream fileToBIS(File file){

    FileInputStream fis = null;
    BufferedInputStream bis =null; 
    try {
        fis = new FileInputStream(file);
        bis = new BufferedInputStream(fis);
    } catch (FileNotFoundException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }   
    return bis;
}

java.io.FileNotFoundException: C:\dev\server\tomcat6\webapps\sample-site (Access is denied)
    at java.io.FileInputStream.open(Native Method)
    at java.io.FileInputStream.(Unknown Source)
    at java.io.FileInputStream.(Unknown Source)
    at controller.ScanEditRegions.fileToBIS(ScanEditRegions.java:52)
    at controller.ScanEditRegions.tidyHTML(ScanEditRegions.java:38)
    at controller.ScanEditRegions.process(ScanEditRegions.java:64)
    at controller.ScanEditRegions.visitAllDirsAndFiles(ScanEditRegions.java:148)
    at controller.Manager.main(Manager.java:10)

like image 376
Ankur Avatar asked Jun 16 '09 05:06

Ankur


2 Answers

Judging by the stacktrace you pasted in your post I'd guess that you do not have the rights to read the file.

The File class allows you to performs useful checks on a file, some of them:

boolean canExecute();
boolean canRead();
boolean canWrite();
boolean exists();
boolean isFile();
boolean isDirectory();

For example, you could check for: exists() && isFile() && canRead() and print a better error-message depending on the reason why you cant read the file.

like image 103
Philipp Avatar answered Sep 18 '22 09:09

Philipp


You might want to make sure that (in order of likely-hood):

  1. The file exists.
  2. The file is not a directory.
  3. You or the Java process have permissions to open the file.
  4. Another process doesn't have a lock on the file (likely, as you would probably receive a standard IOException instead of FileNotFoundException)
like image 20
Bryan Kyle Avatar answered Sep 21 '22 09:09

Bryan Kyle