简体   繁体   English

无法在 Java 中找到和读取文件

[英]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.我对 Java 完全陌生,我正在使用别人的代码来读取二进制文件,但该文件无法打开。 I am running the code in Eclipse under Windows 10 the file is called bookDeepDist.dat I have put it in the project folder.我在 Windows 10 下的 Eclipse 中运行代码,该文件名为 bookDeepDist.dat 我已将其放在项目文件夹中。 The full path name which I have also tried (without success ) is C:\\Users\\Alan\\eclipse-workspace\\readDatabase\\bookDeepDist.dat我也试过(没有成功)的完整路径名是 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错误信息是:无法打开文件 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.问题是, getResourceAsStream() 在运行的 Java 程序的类路径中查找。 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]);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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