How to read/write file in jar [duplicate]

房东的猫 提交于 2020-01-16 07:18:30

问题


Situation: I have a jar, and inside this jar is an file. In this file is an object written that represents the last state of the application (so that the user can pick up where he stopped). I'm using the java Serializable interface in orde to write and read the Object.

My question is: how do I read the file when running the application from the jar.

code so far:

in = new ObjectInputStream(Configuration.class.getResourceAsStream("config.txt"));

Object o = in.readObject();
if(o instanceof Configuration)
    this.configuration = (Configuration) o;

This works perfect, as long as I'm running the application from eclips. When I run the jar, a window is created but nothing is displayed. So I assume an error occured. Does someone know how to read the file?


回答1:


The Preferences API might be a better option for what you're trying to achieve.




回答2:


Is "config.txt" being included in the JAR file when you package it?

I agree with @nneonneo that JAR files aren't the best place to store configuration data (or any other kind of mutable data for that matter). A better alternative might be to store the configuration data in a ".properties" or XML file, outside of the JAR file.



来源:https://stackoverflow.com/questions/17994355/how-to-read-write-file-in-jar

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!