Get FileNotFoundException when initialising FileInputStream with File object

前端 未结 4 1539
盖世英雄少女心
盖世英雄少女心 2020-12-11 18:04

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


        
相关标签:
4条回答
  • 2020-12-11 18:15

    I think you are executing the statement from eclipse or any java IDE and target file is also present in IDE workspace. You are getting the error as Eclipse cant read the target file in the same workspace. You can run your code from command prompt. It should not through any exception.

    0 讨论(0)
  • 2020-12-11 18:22

    This is has to do with file permissions settings in the OS. You've started the java process as a user who has no access rights to the specific directory.

    0 讨论(0)
  • 2020-12-11 18:23

    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)
    0 讨论(0)
  • 2020-12-11 18:35

    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.

    0 讨论(0)
提交回复
热议问题