Java run jar from another jar with passing arguments
I created run1.jar:
package runner;
import java.io.IOException;
import java.io.PrintWriter;
public class Run1 {
public static void main(String[] args) {
int i = Integer.parseInt(args[0]);
System.out.println(i);
try {
PrintWriter writer = new PrintWriter("1.txt", "UTF-8");
writer.println(i);
writer.println(i);
writer.close();
} catch (IOException e) {
// do something
}
}
}
Also I created run2.jar:
package runner;
import java.io.File;
import java.io.IOException;
public class Run2 {
public static void main(String[] args) throws IOException, InterruptedException {
ProcessBuilder pb = new ProcessBuilder("java", "-jar", "C:\\test2\\run1.jar", "1");
pb.directory(new File("C:\\"));
try {
Process p = pb.start();
} catch (IOException e) {
e.printStackTrace();
}
}
}
I have executed this java -jar run2.jar 1 command and am working on it. Waiting for the result is done with this command: java -jar run2.jar which doesn't work.
How to run run2.jar passing parameters from main method to run2.jar?
Mistake:
C:\test2>java -jar run2.jar
Exception in thread "main" java.lang.reflect.InvocationTargetException
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at org.eclipse.jdt.internal.jarinjarloader.JarRsrcLoader.main(JarRsrcLoa
der.java:58)
Caused by: java.lang.ArrayIndexOutOfBoundsException: 0
at runner.Run1.main(Run1.java:9)
source to share
Here we are below two different examples that answer your question
Process proc = Runtime.getRuntime().exec("java -jar C:\\...\\Run1.jar 1");
proc.waitFor();
//2 inputstream for the result and for the errors in subprogram
InputStream in = proc.getInputStream();
InputStream err = proc.getErrorStream();
byte b[]=new byte[in.available()];
in.read(b,0,b.length);
System.out.println(new String(b));
byte c[]=new byte[err.available()];
err.read(c,0,c.length);
System.out.println(new String(c));
ProcessBuilder pb = new ProcessBuilder("java", "-jar", "C:\\...\\Run1.jar", "1");
Process proc2 = pb.start();
proc2.waitFor();
InputStream in2 = proc2.getInputStream();
InputStream err2 = proc2.getErrorStream();
byte b2[]=new byte[in.available()];
in.read(b,0,b.length);
System.out.println(new String(b));
byte c2[]=new byte[err.available()];
err.read(c,0,c.length);
System.out.println(new String(c));
Exit the IDE (Eclipse)
Exiting the command line:
Note: "ok" is my System.out.println which I set to Run1.jar (I saved the file with a capital letter, but you can use your names)
source to share
The error I added to your question refers to the missing argument:, args[0]
line 9 throw ArrayIndexOutOfBoundsException
.
Argument "1" is not passed to run1.jar
Exception stack shows jar-in-jar loader usage, why?
Create jars using Oracle or ANT command line utilities and check again.
source to share