I am trying to copy the Files of a Resources Folder to disk.
final URL url = TemplateUtils.class.getResource("/templates/");
LOG.info(url);
if (url != null) {
final File dir = new File(url.toURI()); //Line 59
this.copyFiles(dir.getAbsolutePath(), dir.getName()); //calls a recursive method to copy all Files in subfolders
Running this code in Eclipse everything is working fine, because the url is:
file:/home/tobias/git/myapp/target/classes/templates/
but after building and running the jar, I get the following error, because the url does not fit anymore:
jar:file:/home/tobias/myapp/myapp-0.0.1-SNAPSHOT-jar-with-dependencies.jar!/templates/
Error:
Caused by: java.lang.IllegalArgumentException: URI is not hierarchical
at java.io.File.<init>(File.java:418)
at myapp.utils.TemplateUtils.copyTemplates(TemplateUtils.java:59)
How do I fix the URI is not hierarchical Error? I already tried to change like they said here: Java Jar file: use resource errors: URI is not hierarchical but then i get a NullPointer at this line:
URL resolvedFileURL = FileLocator.toFileURL(url);
How can I fix this? Maybe there is an easier way to extract this folder to disk?
Solution (but now only working from jar file and not from eclipse anymore): using this class: https://stackoverflow.com/a/3923182/4125191
final File path = new File(PathManager.INSTANCE.getRootPath()
+ "templates/");
path.mkdirs();
try {
LOG.info("Copying Templates...");
final Collection<String> fileList = ResourceList.getResources();
for (final String s : fileList) {
final File newFile = new File(path.toString() + File.separator
+ StringUtils.substringAfterLast(s, File.separator));
newFile.createNewFile();
final String folder = StringUtils.substringAfterLast(
StringUtils.substringBeforeLast(s, File.separator),
File.separator);
final InputStream inStream = TemplateUtils.class
.getResourceAsStream("/" + s);
if (inStream != null) {
Files.copy(inStream, newFile.toPath(),
StandardCopyOption.REPLACE_EXISTING);
inStream.close();
}
this.mapFile(folder, newFile);
}
} catch (final IOException e) {
LOG.error(e.getMessage(), e);
}