0

I'm currently trying to save the entries in a JComboBox after the application terminates. Initially, I was using a BufferedWriter/Reader to do load/save the items that go in the JComboBox. This method did not work because the Jar file did not have access to the src/ folder after compilation. This meant that when running the application from the executable the JComboBox would be empty and unable to save new items.

My next approach was to use the resource folder and leverage the ClassLoader to obtain the resource. Luckily, this approach worked for READING when launch from the jar file and it works for reading and writing in the IDE.

My problem is that the behavior of this application is different when running from IDE and from the jar file. Currently, it can read when launched from the jar but it cannot WRITE to the resource file.

Here's some code for writing to the resource file:

        File file= new File(getClass().getClassLoader().getResource("addresses.txt").toURI());
        FileOutputStream fs = new FileOutputStream(file);
        OutputStreamWriter ow = new OutputStreamWriter(fs);           
        outputWriter = new BufferedWriter(ow);

        for(int i = 0; i < items.length; i++) {
            outputWriter.write(items[i]);
            outputWriter.newLine();
        }
        outputWriter.flush();
        outputWriter.close();
        return true;
    }
Daniel Widdis
  • 8,424
  • 13
  • 41
  • 63
Oscar
  • 31
  • 3
  • 1
    You can't. If you need to save some settings for your application you need to save them on the filesystem. [Similar](https://stackoverflow.com/a/5052359/1759845) – BackSlash Jun 06 '18 at 15:32
  • A hint - JAR file is `zip` archive, so [JarOutputStream](https://docs.oracle.com/javase/7/docs/api/java/util/jar/JarOutputStream.html). In any case, the best approach - create an app specific folder and store your state files in those folder rather then modify your jar file. – Victor Gubin Jun 06 '18 at 15:37
  • @VictorGubin I'm not sure you can use `JarOutputStream`. Likely the jar file gets locked by the JVM, which means that you can't modify it while the application is running. I might be wrong though. – BackSlash Jun 06 '18 at 15:40
  • Thank you. I'm now trying to store the file in the user's home directory using System.getProperty("user.dir"). – Oscar Jun 06 '18 at 15:45
  • Great. That worked :) – Oscar Jun 06 '18 at 15:48
  • @Oscar, Would you consider writing your own answer for your own question and choosing it as the answer? You can still receive UpVotes for your question and additional UpVotes for your answer. This also assists others to see that the question is answered. Thank you. – Rob Jun 06 '18 at 16:17
  • @Oscar the system property "user.dir" is not the user's home directory. See [Java Tutorial on System Properties](https://docs.oracle.com/javase/tutorial/essential/environment/sysprop.html) – D.B. Jun 06 '18 at 16:34

0 Answers0