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.Path
and nio.file.FileSystem
. I've looked up several things online, but what I can't figure out is how to handle FileSystem
s 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 InputStream
s? Or should it always be closed and later "reloaded" when a file will actually be read.
My assumption is that keeping multiple ZipFileSystem
s 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)FileSystem
s I'm not understanding yet.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With