Created
June 25, 2018 20:24
-
-
Save alexandreaquiles/5670eee1a8b75b52aa266032ee7c5720 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class FileUtils { | |
public static String getResourceContents(String resource) throws URISyntaxException, IOException { | |
Path resourcePath = getResourceAsPath(resource); | |
return getPathContents(resourcePath); | |
} | |
private static Path getResourceAsPath(String resource) throws URISyntaxException, IOException { | |
URI uri = FileUtils.class.getResource(resource).toURI(); | |
System.out.println(uri.getScheme()); | |
if (isResourceInJar(uri)) { | |
return getResourceFromJar(uri); | |
} else { | |
return Paths.get(uri); | |
} | |
} | |
private static boolean isResourceInJar(URI uri) { | |
return uri.getScheme().equals("jar"); | |
} | |
private static Path getResourceFromJar(URI fullURI) throws IOException { | |
// see http://stackoverflow.com/a/22605905 | |
String[] uriParts = fullURI.toString().split("!"); | |
URI jarURI = URI.create(uriParts[0]); | |
FileSystem fs; | |
try { | |
fs = FileSystems.newFileSystem(jarURI, Collections.<String, String>emptyMap()); | |
} catch (FileSystemAlreadyExistsException ex) { | |
fs = FileSystems.getFileSystem(jarURI); | |
} | |
String resourceURI = uriParts[1]; | |
return fs.getPath(resourceURI); | |
} | |
private static String getPathContents(Path path) throws IOException { | |
return new String(Files.readAllBytes(path)); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment