简体   繁体   中英

Cannot find and read file in Java

I am completely new to Java and I am using somebody elses code to read a binary file but the file will not open. I am running the code in Eclipse under Windows 10 the file is called bookDeepDist.dat I have put it in the project folder. The full path name which I have also tried (without success ) is C:\\Users\\Alan\\eclipse-workspace\\readDatabase\\bookDeepDist.dat

The code that fails is:

public void openBook() throws IOException {

    file = getClass().getResourceAsStream(BOOKPATH[bookNr]);
    if (file == null)
        throw (new IOException("Could not open File "+BOOKPATH[bookNr]));
}

The error message is: Could not open File bookDeepDist.dat

so it seems to be trying to open the correct file. Can anybody give me any idea what could be going wrong?

The problem is, that getResourceAsStream() looks in the classpath of the running Java program. That's why it is working, when you put the file in the project folder. What you want, is a stream of the file outside of the program's classpath.

Instead of

file = getClass().getResourceAsStream(BOOKPATH[bookNr]);

try using

file = new FileInputStream(BOOKPATH[bookNr]);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM