Skip to content

Instantly share code, notes, and snippets.

@frgomes
Last active September 10, 2015 17:06
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 frgomes/5c8c108c6fc6573042cc to your computer and use it in GitHub Desktop.
Save frgomes/5c8c108c6fc6573042cc to your computer and use it in GitHub Desktop.
Java - Copy resources from classpath onto a temporary directory
import java.io.File;
import java.io.IOException;
import java.net.URL;
import org.apache.commons.io.FileUtils;
public class Resource {
private static java.net.URLStreamHandler cp = new org.ops4j.pax.url.classpath.Handler();
private final URL url;
private final String paths[];
public Resource(String resource) throws IOException {
this.url = new URL(null, "classpath:" + resource, cp);
this.paths = url.getPath().split("[\\\\/]");
}
public URL asURL() {
return url;
}
/**
* Creates a temporary directory out of a resource.
*/
public File asTmpDir() throws IOException {
return asTmpDir(paths);
}
/**
* Creates a temporary file out of a resource.
*/
public File asTmpFile() throws IOException {
File dir = asTmpDir(java.util.Arrays.copyOfRange(paths, 0, paths.length - 1));
File file = new File(dir.getAbsolutePath(), paths[paths.length-1]);
FileUtils.copyURLToFile(url, file);
return file;
}
private File asTmpDir(String[] items) throws IOException {
StringBuilder sb = new StringBuilder();
sb.append(System.getProperty("java.io.tmpdir"));
sb.append('/').append(java.lang.management.ManagementFactory.getRuntimeMXBean().getName());
for (String item : items) sb.append(item).append('/');
File dir = new File(sb.toString());
dir.mkdirs();
return dir;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment