简体   繁体   中英

Packaging a file in a JAR and then moving it to the correct directory

I've looked everywhere for this but I can't seem to figure it out.

I'm making a application in Java that uses the Midi library. In order to run this application the user has to have a SoundBank file (soundbank.gm) in their JRE installation folder in lib/audio. I don't want to make the user have to figure this out themselves, so I was hoping I could just package the soundbank as a resource in the application and when the application is started, I could move it to the correct directory programmatically if it wasn't there.

So first I need to know how to package a resource as in the JAR. Then I need to know how to copy the resource to a different directory. I know how to copy normal files, but I'm not sure how I'd be able to access a file in a JAR.

Any help would be appreciated. I'm using eclipse BTW to export a Runnable JAR.

EDIT: I just figured out the reason my file wasn't being packaged in the JAR was because I didn't declare it as a source folder in eclipse. Now how do I access that file in Java? Can I simply treat the JAR name as a folder name?

In order to access resource packaged in JAR file (or just anywhere in classpath) from Java application you could use:

getClass().getResourseasStream("path/to/resource");

If resource is in the same package as your class you just need resource name without any path (eg like current directory) if resource is in the different package you could use absolute path. See the javadoc for Class.getResourseAsStream(). Once you got the stream you could read from it, copy it etc. as you normally would with any stream.

One direct way of doing that is to access your java resource as a stream and copy it where you want, using for example the commons IOUtils utility class:

InputStream is = MyInstallerClass.class.getResourceAsStream("/path/to/my/resource");
OutputStream os = new FileOutputStream("/path/to/install/directory");
org.apache.commons.io.IOUtils.copy(is,os);

Let's say you package soundback.gm underneath "resources" in your JAR.

You could then use the following to access that file...

ClassLoader cl = this.getClass().getClassLoader();
InputStream is = cl.getResourceAsStream("resources/soundback.gm");

You could then convert that InputStream into a file via this...

OutputStream out = new FileOutputStream(new File("/lib/audio/soundback.gm"));

int read = 0;
byte[] bytes = new byte[1024];

while ((read = is.read(bytes)) != -1) {
   out.write(bytes, 0, read);
}

is.close();
out.flush();
out.close();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM