将 txt 文件添加到可运行的 JAR 文件

Add txt files to a runnable JAR file

我正在尝试制作一个可运行的 jar 文件,但我的 .txt 文件有问题。

我的程序也有图像,但幸运的是我已经想出了如何管理它们。我在他们身上使用了类似的东西,它在 Eclipse 和 jar 上都工作得很好:

logoLabel.setIcon(new ImageIcon(getClass().getResource("/logo.png")));

我的问题是当我的 classes 中有这样的东西时:

try {
    employeeList =  (TreeSet<Employee>) ListManager.readFile("list/employeeList.txt");
} catch (ClassNotFoundException i) {
    i.printStackTrace();
} catch (IOException i) {
    i.printStackTrace();
}

在我用来读取 .txt 文件中序列化列表的 class ListManager 中:

public static Object readFile(String file) throws IOException, ClassNotFoundException {
    ObjectInputStream is = new ObjectInputStream(new FileInputStream(file));
    Object o = is.readObject();
    is.close();
    return o;
}

我也有类似的方法写在文件里

我已经尝试了在这里找到的几种组合:

How to include text files with Executable Jar

Creating Runnable Jar with external files included

Including a text file inside a jar file and reading it

我也尝试过使用斜杠、不使用斜杠、使用 openStream、不使用 openStream...但是或者我得到一个 NullPointerException 或者它根本无法编译...

可能有些愚蠢,或者可能是我对 URL class 工作原理的概念错误,我是编程新手...

非常感谢您的建议!

编辑:

又是我...Raniz 给出的答案正是我所需要的,而且效果很好,但现在我的问题是我用来写入文件的方法...

public static void writeFile(Object o, String file) throws IOException {
    ObjectOutputStream os = new ObjectOutputStream(new FileOutputStream(file));
    os.writeObject(o);
    os.close();
}

try {
   ListManager.writeFile(employeeList.getEmployeeList(), "lists/employeeList.txt");
} catch (IOException i) {
   i.printStackTrace();
}

你能帮帮我吗?我不知道我应该用什么来代替FileOutputStream,因为我觉得问题又来了,对吗?

非常感谢!

是的,如果你想从 jar 文件中读取资源,你不应该使用 FileInputStream。也许你应该添加一个 readResource 方法:

public static Object readResource(Class clazz, String resource)
    throws IOException, ClassNotFoundException {
  try (ObjectInputStream is =
           new ObjectInputStream(clazz.getResourceAsStream(resource))) {
     return is.readObject();
  }
}

(我还建议更新您的 readFile 方法以使用 try-with-resources 块 - 目前如果出现异常您不会关闭流...)

请注意,当您说 "I also have a similar method to write in the files" - 您 将无法 轻松写入 jar 文件中的资源。

问题是您正在尝试将 JAR 存档中的文件作为文件系统中的文件进行访问(因为这就是 FileInputStream 的用途),但这是行不通的。

您可以将 readFile 转换为使用 URL 并让 URL 为您打开流:

public static Object readFile(URL url) throws IOException, ClassNotFoundException {
    ObjectInputStream is = new ObjectInputStream(url.openStream());
    Object o = is.readObject();
    is.close();
    return o;
}

您还应该将代码放在 try 语句中,因为如果发生 IOException 目前它不会关闭流:

public static Object readFile(URL url) throws IOException, ClassNotFoundException {
    try(ObjectInputStream is = new ObjectInputStream(url.openStream())) {
        Object o = is.readObject();
        return o;
    }
}

try {
    employeeList =  (TreeSet<Employee>) ListManager.readFile(getClass().getResource("/list/employeeList.txt"));
} catch (ClassNotFoundException i) {
    i.printStackTrace();
} catch (IOException i) {
    i.printStackTrace();
}

I also have a similar method to write in the files.

如果文件在 JAR 中,那将不起作用,因此您可能应该考虑将文件放在 JAR 之外。