Search code examples
javaeclipsejarpreferencesfileoutputstream

Is there a way to write to a file that is inside a JAR?


I am currently using the java class Preferences to maintain preferences inside of our java application. It is simple, and currently only contains 2 key/value pairs. Some of the higher ups on this project have requested to keep the preferences.xml file inside of the JAR, to make it a clean running, so everything would be self contained within the JAR (users do not need to be able to access this file).

I know that preferences has an import using an InputStream, and an export using an OutputStream. Is there anyway to edit the file inside the jar using the outputStream?


Solution

  • A JAR file is a zip folder, so it can be extracted and worked upon using the java.util.zip package.

    However, a running jar may be write protected, preventing content modification.

    It is better suited to store configuration in a corresponding location in the operating system. On windows, the common location is the windows registry.

    There is a Java library for editing the registry as shown in this answer .

    Library Source: https://github.com/apache/npanday/tree/trunk/components/dotnet-registry/src/main/java/npanday/registry

    To store config on other operating systems, you can use a file inside a folder named after your application.

    • Common Location on Linux: '~/.config' folder
    • Common location on Mac: '~/Library/Application Support' folder.