Last active
September 10, 2015 17:06
-
-
Save frgomes/5c8c108c6fc6573042cc to your computer and use it in GitHub Desktop.
Java - Copy resources from classpath onto a temporary directory
This file contains 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
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