I’m working on a Java GUI for an OCaml executable. I need to execute a binary that resides in a .jar. It turns out that binaries cannot be executed while in the .jar. The binaries have to be copied from the .jar and placed on the host machine. I chose to place the binaries in a temporary file. Then the .jar can use system commands to interact with binaries it needs to execute.
The following thread led me in this direction. Thank you, stackoverflow.com!
http://stackoverflow.com/questions/4764347/extract-and-load-dll-from-jar
Here is some example code to copy a file from your .jar to the host machine.
try { // Get a handle (as a stream) on the binary you want to move from the .jar to a folder on the system InputStream in = Toolkit.getDefaultToolkit().getClass().getResourceAsStream("/path/to/binary/in/jar"); // Get a handle on where you want the binary to be saved. File fileOut = new File("/path/you/want/to/place/your/lib/binaryname"); // make sure the path to the file exists fileOut.mkdirs(); // Create an output stream to put data into. OutputStream out = new FileOutputStream(fileOut); // Copy the bytes from our input stream to our output stream. byte[] buf = new byte[1024]; int len; while((len = in.read(buf)) > 0) { out.write(buf, 0, len); } in.close(); out.close(); } catch (Exception e) { //handle }
After a successful copy you can then use the Runtime to execute your command.
try { String command = "path/to/binary -args"; Process p = Runtime.getRuntime().exec(command); BufferedReader stdInput = new BufferedReader(new InputStreamReader(p.getInputStream())); BufferedReader stdError = new BufferedReader(new InputStreamReader(p.getErrorStream())); String s = null; while ((s = stdInput.readLine()) != null) { System.out.println(s); } // read any errors from the attempted command System.out.println("Here is the standard error of the command (if any):n"); while ((s = stdError.readLine()) != null) { System.err.println(s); } } catch(Exception e){ //handle }