1

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?

Joris W
  • 517
  • 3
  • 16
  • 5
    It's a really bad idea to store configuration files that need to be updated in a JAR. Besides, it may be *impossible* to write to the JAR on some platforms as it will be in use while the JVM runs. Best use an external configuration file. – nneonneo Aug 01 '13 at 12:48
  • Assuming your file is exported into the jar `getResourceAsStream` should find it. Try to get more informations about what your application is doing ... errors / stacketrace and porst here. And for writing, this has been answered many times on SO, it is not possible. – A4L Aug 01 '13 at 12:49

2 Answers2

2

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

Philippe Marschall
  • 4,452
  • 1
  • 34
  • 52
0

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.

Michael
  • 34,873
  • 17
  • 75
  • 109