I want to copy a file from a jar. The file that I am copying is going to be copied outside the working directory. I have done some tests and all methods I try end up with 0 byte files.
EDIT: I want the copying of the file to be done via a program, not manually.
You can use getResource() to obtain a URL for a file on the classpath, or getResourceAsStream() to get an InputStream instead. Show activity on this post. You could read the contents of a JAR file using the JarFile class. Show activity on this post.
If you add the resources directory in the jar file (so it is under the /resources folder in the jar, and if /src/main is in your build path in eclipse, then you should be able to reference your file as: getClass(). getResource("/resources/filename. txt");
First of all I want to say that some answers posted before are entirely correct, but I want to give mine, since sometimes we can't use open source libraries under the GPL, or because we are too lazy to download the jar XD or what ever your reason is here is a standalone solution.
The function below copy the resource beside the Jar file:
/** * Export a resource embedded into a Jar file to the local file path. * * @param resourceName ie.: "/SmartLibrary.dll" * @return The path to the exported resource * @throws Exception */ static public String ExportResource(String resourceName) throws Exception { InputStream stream = null; OutputStream resStreamOut = null; String jarFolder; try { stream = ExecutingClass.class.getResourceAsStream(resourceName);//note that each / is a directory down in the "jar tree" been the jar the root of the tree if(stream == null) { throw new Exception("Cannot get resource \"" + resourceName + "\" from Jar file."); } int readBytes; byte[] buffer = new byte[4096]; jarFolder = new File(ExecutingClass.class.getProtectionDomain().getCodeSource().getLocation().toURI().getPath()).getParentFile().getPath().replace('\\', '/'); resStreamOut = new FileOutputStream(jarFolder + resourceName); while ((readBytes = stream.read(buffer)) > 0) { resStreamOut.write(buffer, 0, readBytes); } } catch (Exception ex) { throw ex; } finally { stream.close(); resStreamOut.close(); } return jarFolder + resourceName; }
Just change ExecutingClass to the name of your class, and call it like this:
String fullPath = ExportResource("/myresource.ext");
As answered by GOXR3PLUS and noted by Andy Thomas you can achieve this with:
Files.copy( InputStream in, Path target, CopyOption... options)
See GOXR3PLUS answer for more details
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With