Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to work with (Zip)FileSystems - keep open or re-open as needed?

Tags:

java

java-8

jar

nio

I'm working on a project with Java 8. The component I'm working on provides access to files, e.g. config files, that are classpath resources.

It's my first time working with nio.file.Pathand nio.file.FileSystem. I've looked up several things online, but what I can't figure out is how to handle FileSystems correctly, because to access a file using Path the `FileSystem´ must be/remain open.

The overall use case is that several consumers can request the same or different config files at any time. The access to a file resource will be provided using a Path that is a member of a MyResource object.

This is a rough draft of how a Path is created atm.

Path getResource(fileNameStr) {
  Path result = null;

  URI uri =  ClassLoader.getSystemResource(fileNameStr).toURI();

  Map<String, String> env = new HashMap<String, String>(); 
  env.put("create", "true");

  FileSystem zipfs = FileSystems.newFileSystem(uri);
  result = Paths.get(uri);

  // question: close zipfs or keep open?

  return result;
}

What I would like to understand: Can a (Zip)FileSystem remain open to ease further working with a Path instance and e.g. needed InputStreams? Or should it always be closed and later "reloaded" when a file will actually be read.

My assumption is that keeping multiple ZipFileSystems open indefinitely is not intended, but not keeping them open means that consumers must always check if a needed ZipFileSystem already exist and if not, they must create one. Also the closing of a ZipFileSystem must be managed if several consumers access the same JAR simultaneously . It would be possible for me to add further functionalities to ease the file access, but I'd assume if that is needed, it would already exist. Therefore there must be an answer/process of working with (Zip)FileSystems I'm not understanding yet.

like image 611
CJOverflow Avatar asked Aug 31 '25 04:08

CJOverflow


1 Answers

May be you need a caching mechanism for FileSystem instances that should remain opened for subsequent use, and/or add a count to track the number of consumers/users of the file, once it is 0 (or the file no longer used) you can close it

like image 159
biiyamn Avatar answered Sep 02 '25 19:09

biiyamn