Home > Software design >  Java read and write to the resource folder
Java read and write to the resource folder

Time:09-13

When someone opens my jar up I am opening a file selector gui so they can choose where they want to store their jar's files like config files and such. This should only take place the first time they open the jar. However, one issue with this approach is that I would have no way to know if it's their first time opening the jar since I will need to save the selected path somewhere. The best solution to this sounds like saving the selected path inside a file in the resource folder which is what I am having issues with. Reading and writing to this resource file will only need to be done when the program is actually running. These read and write operations need to work for packaged jar files (I use maven) and in the IDE.

I am able to read a resources file inside of the IDE and then save that file to the designated location specified in the file selector by doing this. However, I have not been able to do the same from a jar despite trying multiple other approaches from other threads.

        ClassLoader classloader = Thread.currentThread().getContextClassLoader();
        InputStream is = classloader.getResourceAsStream("config.yml");
        try {
            if(is != null) {
                Files.copy(is, testFile.toPath(), StandardCopyOption.REPLACE_EXISTING);
                is.close();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }

So just to clarify when my project is loaded I need to listen for the user to select a valid path for files like my config. Then I want to write my config to that path which I can do from my IDE and is shown above but I cant figure this out when I compile my project into a jar file since I always receive a file not found error in my cmd. However, the main point of this post is so that I can figure out how to save that selected path to my resource folder to a file (it can be json, yml or whatever u like). In the code above I was able to read a file but I have no idea how to go from that to get the files path since then reading and writing to it would be trivial. Also keep in mind I need to be able to read and write to a resource folder from both my IDE and from a compiled jar.

The following code shows my attempt at reading a resource from a compiled jar. When I added a print statement above name.startWith(path) I generated a massive list of classes that reference config.yml but I am not sure which one I need. I assume it has to be one of the paths relating to my project or possible the META-INF or META-INF/MANIFEST.MF path. Either way how am I able to copy the file or copy the contents of the file?

  final String path = "resources/config.yml";
  final File jarFile = new File(getClass().getProtectionDomain().getCodeSource().getLocation().getPath());

    if(jarFile.isFile()) {  // Run with JAR file
        try {
            final JarFile jar = new JarFile(jarFile);
            final Enumeration<JarEntry> entries = jar.entries(); //gives ALL entries in jar
            while(entries.hasMoreElements()) {
                final String name = entries.nextElement().getName();
                if (name.startsWith(path)) { //filter according to the path
                    System.out.println(name);
                }
            }
            jar.close();
        } catch (IOException exception) {
            exception.printStackTrace();
        }
    }

Also if you were wondering I got the above code from the following post and my first block of code I pasted above is actually in the else statement since the IDE code from that post also did not work. How can I access a folder inside of a resource folder from inside my jar File?

CodePudding user response:

You can't write to files inside your JAR file, because they aren't actually files, they are ZIP entries.

The easiest way to store configuration for a Java application is to use Preferences:

Preferences prefs = Preferences.userNodeForPackage(MyApp.class);

Now all you have to do is use any of the get methods to read, and put methods to write.

CodePudding user response:

There is absolutely no need to write files into your resource folder inside a jar. All you need to have is a smart classloader structure. Either there is a classloader that allows changing jars (how difficult is that to implement?), or you just setup a classpath that contains an empty directory before listing all the involved jars.

As soon as you want to change a resource, just store a file in that directory. When loading the resource next time, it will be searched on the classpath and the first match is returned - in that case your changed file.

Now it could be that your application needs to be started with that modified classpath, and on top of that it needs to be aware which directory was placed first. You could still setup that classloader structure within a launcher application, which then transfers control to the real application loaded via the newly defined classloader.

CodePudding user response:

You could also check on application startup whether a directory such as ${user.home}/${application_name}/data exists.

If not, create it by extracting a predefined zip into this location. Then just run your application which would load/write all the data in this directory.

No need to read/write to the classpath. No need to include 3rd party APIs. And modifying this initial data set would just mean to distribute a new zip to be extracted from.

  • Related