繁体   English   中英

在什么情况下,文件会放在JAR的资源中,但无法在类的ClassLoader中访问?

[英]In what situation is a file placed in the resources of a JAR, but is not accessible in a class' ClassLoader?

我只是想使用this.class.getResourceAsStream(filename)将一个简单的.txt文件读入我的Java项目中。 我在main / resources中有几个文件,当我尝试将它们作为输入流时,几乎所有文件都返回一个对象。 我无法读入的唯一对象是我的文本文件。

我已经将该文件与所有其他可由类加载器读取的资源文件一起放置,但是无论出于何种原因,似乎都没有将该文件放置在类的classLoader中。 如果我解压缩该jar文件,则该文件仍与所有其他资源包含在该jar文件中的同一目录中,因此似乎可以正确构建该文件。

我想我要问的是在什么时候告诉Java我想将哪些文件作为资源包含在类的ClassLoader中? 如果事物放置在正确的位置(例如,主/资源),那么在构建jar时是否应该做些什么?

这是代码的样子,分别是返回值,当运行它可以找到的文件和找不到它的文件时,它们都位于同一位置。

// This is not found. Both are placed at src/main/resources
def tmpDict = this.class.getResourceAsStream("dict.txt")

println tmpDict // null

// This is found
def tmpDict2 = this.class.getResourceAsStream("calc.config")

println tmpDict2 // sun.net.www.protocol.jar.JarURLConnection$JarURLInputStream@2dae5a79

没有更多信息,我会说这条路是错误的。 当我只使用“ file.txt”作为路径时,它得到了NPE

用这种方法从流中读取。 该文件位于\\src\\main\\resources\\static\\file.txt此文件在eclipse中工作,打包到jar中,也在那里工作。

public String getFile() throws Exception {
    InputStream in = Controller.class.getClassLoader().getResourceAsStream("static/file.txt");
    BufferedReader reader = new BufferedReader(new InputStreamReader(in, Charset.defaultCharset()));
    StringBuilder out = new StringBuilder();
    String line;
    while ((line = reader.readLine()) != null) {
        out.append(line);
    }        
    return out.toString();
}

一些非常基本的检查:

该文件必须区分大小写(因为它不是Windows文件),并且文件名的特殊字符可能很麻烦。 还要检查项目中的文件扩展名是否没有两次(.txt.txt-Windows隐藏该扩展名)。

检查getResourceAsStream("/a/b/c/A.txt")确实为空。

如果不是,则读数可能在编码上出错。

暂无
暂无

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

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