Skip to content

Instantly share code, notes, and snippets.

@alexandreaquiles
Created June 25, 2018 20:24
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save alexandreaquiles/5670eee1a8b75b52aa266032ee7c5720 to your computer and use it in GitHub Desktop.
Save alexandreaquiles/5670eee1a8b75b52aa266032ee7c5720 to your computer and use it in GitHub Desktop.
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