Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /**
- * Developer notes on {@link FileSystemNotFoundException}:
- * ================================================================================================================
- * {@link FileSystemNotFoundException} will be thrown by {@link Paths#get(URI)} if you are trying to load a resource
- * that is located within a Jar.
- * https://stackoverflow.com/questions/15713119/java-nio-file-path-for-a-classpath-resource
- *
- * {@link java.nio.file.FileSystem} implements {@link Closeable}. That said, I am not using it inside a
- * <code>try-with-resource</code> statement because the {@link java.nio.file.FileSystem} is only created once - and
- * then other resources in the same area can be loaded with the same {@link java.nio.file.FileSystem}
- * (ie you don't have to repeatedly create and close {@link java.nio.file.FileSystem}s).
- *
- * Also, closing {@link java.nio.file.FileSystem}s are problematic, because the associated {@link Path} can then
- * no longer be used.
- * ================================================================================================================
- */
- private static Path getPathFromUri(URI fileUri) {
- Assert.isNotNull(fileUri);
- Path fileOrDirectory = null;
- try {
- fileOrDirectory = Paths.get(fileUri);
- } catch (FileSystemNotFoundException e) {
- // Not sure how threadsafe FileSystems are, so being safe, rather than sorry.
- nfsLock.lock();
- try {
- // Try again, maybe another thread has created the required FileSystem
- fileOrDirectory = Paths.get(fileUri);
- } catch (FileSystemNotFoundException fsnfe) {
- // Other threads have not yet created the required FileSystem
- if (logger.isInfoEnabled()) {
- logger.info("Creating a FileSystem for classpath resource: " + fileUri);
- }
- try {
- FileSystems.newFileSystem(fileUri, Collections.<String, Object>emptyMap());
- } catch (IOException ioe) {
- String errorMessage = "A problem occurred creating a FileSystem for classpath resource: " + fileUri;
- throw new RuntimeException(errorMessage, ioe);
- }
- // Try again, now that the FileSystem has been created
- fileOrDirectory = Paths.get(fileUri);
- } finally {
- nfsLock.unlock();
- }
- }
- return fileOrDirectory;
- }
- private final static ReentrantLock nfsLock = new ReentrantLock();; // Lock for creating new FileSystems
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement