Skip to content
Advertisement

Copy directory from a jar file

I have recently developed an application and created the jar file.

One of my classes creates an output directory, populating it with files from its resource.

My code is something like this:

// Copy files from dir "template" in this class resource to output.
private void createOutput(File output) throws IOException {

    File template = new File(FileHelper.URL2Path(getClass().getResource("template")));
    FileHelper.copyDirectory(template, output);
}

Unfortunately this doesn’t work.

I tried the following without luck:

While writing this I was thinking about instead of having a template dir in the resource path having a zip file of it. Doing it this way I could get the file as an inputStream and unzip it where I need to. But I am not sure if it’s the correct way.

Advertisement

Answer

I think your approach of using a zip file makes sense. Presumably you’ll do a getResourceAsStream to get at the internals of the zip, which will logically look like a directory tree.

A skeleton approach:

InputStream is = getClass().getResourceAsStream("my_embedded_file.zip");
ZipInputStream zis = new ZipInputStream(is);
ZipEntry entry;

while ((entry = zis.getNextEntry()) != null) {
    // do something with the entry - for example, extract the data 
}
User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement