【发布时间】:2015-07-11 03:16:58
【问题描述】:
我正在尝试制作一个可运行的 jar 文件,但我的 .txt 文件有问题。
我的程序也有图像,但幸运的是我已经知道如何管理它们。我正在与他们一起使用这样的东西,它在 Eclipse 和 jar 中都可以正常工作:
logoLabel.setIcon(new ImageIcon(getClass().getResource("/logo.png")));
我的问题是当我在我的一门课上遇到这样的事情时:
try {
employeeList = (TreeSet<Employee>) ListManager.readFile("list/employeeList.txt");
} catch (ClassNotFoundException i) {
i.printStackTrace();
} catch (IOException i) {
i.printStackTrace();
}
这在我用来读取在 .txt 文件中序列化的列表的 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 类如何工作的概念错误,我是编程新手...
非常感谢您的建议!
编辑:
又是我……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,因为我觉得问题又来了,对吗?
非常感谢!
【问题讨论】:
-
我想我知道你为什么要这么做。但这是一种错误的方法,您应该将您的外部文件(例如 config、txt 等)放在特定于您的应用程序的文件夹中。例如在 userhome/.yourappliactionname