Java 确保JAR中包含文本文件

Java 确保JAR中包含文本文件,java,jar,Java,Jar,很抱歉,如果这是重复的,我一直在四处搜索,没有找到任何有效的 我一直在尝试将项目导出为JAR文件,其中包括从文本文件读取信息。做了一些之后,我使用CLASSNAME.class.getClassLoader().getResourceAsStream(“textFile.txt”)将我的阅读器从FileReader改为InputStreamReader。(我也知道它应该在不使用getClassLoader()方法的情况下工作)但是,getResourceAsStream(“textFile.tx

很抱歉,如果这是重复的,我一直在四处搜索,没有找到任何有效的

我一直在尝试将项目导出为JAR文件,其中包括从文本文件读取信息。做了一些之后,我使用
CLASSNAME.class.getClassLoader().getResourceAsStream(“textFile.txt”)
将我的阅读器从FileReader改为InputStreamReader。(我也知道它应该在不使用
getClassLoader()
方法的情况下工作)但是,
getResourceAsStream(“textFile.txt”)
返回null,当我尝试使用BufferedReader读取它时抛出NullPointerException

据我所知,这是因为我的文本文件实际上不在JAR中。但是当我这么做的时候,我仍然得到一个空点异常。我还尝试将包含文件的文件夹添加到构建路径,但是。我不知道如何检查文件是否确实在JAR中,如果不是,如何将它们放入JAR中,以便找到并正确读取它们

作为参考,我目前在MacBook Air上使用Eclipse Neon,下面是我尝试读取文本文件但失败的代码:

public static void addStates(String fileName) {
        list.clear();
        try {
            InputStream in = RepAppor.class.getClassLoader().getResourceAsStream("Populations/" + fileName);
            BufferedReader reader = new BufferedReader(new InputStreamReader(in));
            /*
             * NOTE: A Leading slash indicates the absolute root of the directory, which is on my system
             * Don't use a leading slash if the root is relative to the directory
             */
            String line;
            while(!((line = reader.readLine()) == null)) {
                list.add(line);
        }
        reader.close();
    } catch (IOException e) {
        JOptionPane.showMessageDialog(null, "The file, " + fileName + ", could not be read.", "Error", JOptionPane.ERROR_MESSAGE);
    } catch (NullPointerException n) {
        JOptionPane.showMessageDialog(null, "Could not find " + fileName + ".\nNull Pointer Exception thrown", "Error", JOptionPane.ERROR_MESSAGE);
    }
}

感谢您的考虑,我非常感谢并欢迎您提供任何反馈。

检查.jar文件内容的方法有很多

大多数IDE都有一个“文件”部分,您可以在其中简单地展开一个.jar文件,就好像它是一个目录一样

如果您的执行路径中有JDK的
bin
子目录,则可以在终端中使用
jar
命令:

jar tf /Users/AaronMoriak/repappor.jar
每个.jar文件实际上都是一个具有不同扩展名的zip文件(以及一个或多个特定于Java的特殊条目)。因此,任何处理zip文件的命令都可以处理.jar文件

由于您在Mac上,因此可以访问Unix
unzip
命令。在终端中,您可以简单地执行以下操作:

unzip -v /Users/AaronMoriak/repappor.jar
-v
选项表示“查看但不提取”。)

如果.jar文件包含大量条目,则可以限制上述命令的输出:

unzip -v /Users/AaronMoriak/repappor.jar | grep Populations
关于前导斜杠的代码注释不太正确。但是,如果删除getClassLoader()部分,则注释会更加正确:

// Change:
// RepAppor.class.getClassLoader().getResourceAsStream
// to just:
// RepAppor.class.getResourceAsStream

// Expects 'Populations' to be in the same directory as the RepAppor class.
InputStream in = RepAppor.class.getResourceAsStream("Populations/" + fileName);

// Expects 'Populations' to be in the root of the classpath.
InputStream in = RepAppor.class.getResourceAsStream("/Populations/" + fileName);