问题
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