'Export a .jar file to a temp file
I have two programms "a" and "b" bot compiled to fatJar files. "b" is added as resource to "a". I now want "a" to execute "b" using a process builder. As far as I understand it I cannot directly give the process builder the "b" jar for it doesn't exist in the regular windows file system. The suggested solution to this is to access "b" as resource and write its content to a temp file and then hand the temp file to the process builder.
My question is: how do i copy the fatJar "b" into a temp file in a way it stays executionable? My current approach looks like this:
try {
Path tempFile = Files.createTempFile("b", ".jar");
InputStream stream = Main.class.getClassLoader().getResourceAsStream("b.jar");
try (InputStreamReader streamReader =
new InputStreamReader(stream, StandardCharsets.UTF_8);
BufferedReader reader = new BufferedReader(streamReader)) {
String line;
while ((line = reader.readLine()) != null) {
Files.write(tempFile, reader.readLine().getBytes(StandardCharsets.UTF_8));
}
} catch (IOException e) {
e.printStackTrace();
}
ProcessBuilder processBuilder = new ProcessBuilder("java", "-jar", tempFile.getFileName().toString());
processBuilder.directory(new File(tempFile.getParent().toString()));
Process process = processBuilder.start();
processBuilder.redirectErrorStream(true);
System.out.println(process.isAlive());
The process.isAlive() call confirms the process is running however the process doesn't function as it should (it should build up a two way communication via the input and output streams but i won't get any answer from the running process). Does anyone know if there is an better approach to the whole situation or if my way of copying the .jar to the temp file is wrong?
Solution 1:[1]
Ok so meanwhile i figured it out. Turns out the Buffered reader caused the problem. The below code works fine now.
Path tempFile = Files.createTempFile("b", ".jar");
InputStream stream = Main.class.getClassLoader().getResourceAsStream("b.jar");
byte[] line = stream.readAllBytes();
Files.write(tempFile, line);
ProcessBuilder processBuilder = new ProcessBuilder("java", "-jar", tempFile.getFileName().toString());
processBuilder.directory(new File(tempFile.getParent().toString()));
Process process = processBuilder.start();
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Peter Csala |