在jar文件中包含一个文本文件并读取它 [英] Including a text file inside a jar file and reading it

查看:128
本文介绍了在jar文件中包含一个文本文件并读取它的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


可能重复:

Java资源作为文件

我是Java的新手我想在Jar文件中获取一个文本文件。

I am kind of new to Java and I am trying to get a text file inside a Jar file.

当我执行我的jar时,我必须将我的文本文件放在与jar fil相同的文件夹中。如果文本文件不在那里,我将得到 NullPointerException ,我想避免。

At the moment when I execute my jar I have to have my text file in the same folder as the jar fil. If the text file is not there I'll get a NullPointerException, which I want to avoid.

我是什么想要做的是在jar中获取txt文件,所以我不会有这个问题。我尝试了一些指南,但它们似乎没有用。我当前的读取功能如下:

What I want to do is to get the txt file inside the jar so I wont have this problem. I tried some guides but they didn't seem to work. My current read function goes like this:

public static HashSet<String> readDictionary()
{
    HashSet<String> toRet = new HashSet<>();
     try
     {
            // Open the file that is the first 
            // command line parameter
            FileInputStream fstream = new FileInputStream("Dictionary.txt");
        try (DataInputStream in = new DataInputStream(fstream)) {
            BufferedReader br = new BufferedReader(new InputStreamReader(in));
            String strLine;
            //Read File Line By Line
            while ((strLine = br.readLine()) != null)   {
            // Read Lines
                toRet.add(strLine);
            }
        }
            return toRet;
     }
     catch (Exception e)
     {//Catch exception if any
            System.err.println("Error: " + e.getMessage());
     } 
     return null;
}


推荐答案

不要试图找一个文件作为Jar文件中的文件。请改用资源。

Don't try to find a file as a "file" in a Jar file. Use resources instead.

获取对类或类加载器的引用,然后在类或类加载器调用 getResourceAsStream(/ *资源地址*) /);

Get a reference to the class or class loader and then on the class or class loader call getResourceAsStream(/* resource address */);.

你也应该研究你的搜索技巧,因为这已经被无数次地询问和回答了。事实上,我们应该关闭这个问题,因为我没有看到它增加了已经存在于SO上的讨论。

You also should work on your search skills, as this has been asked and answered here innumerable times. In fact we should probably close this question as I don't see it adding to discussions already present on SO.

这篇关于在jar文件中包含一个文本文件并读取它的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆