我已经生成了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
}
}
}
我也生成了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();
}
}
}
我使用此命令 java -jar run2.jar 1 运行并运行它。 期望结果正在运行此命令: java -jar run2.jar 谁不工作。
如何在run2.jar中使用main方法内部传递参数来运行run2.jar?
错误是:
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)
答案 0 :(得分:1)
我们在下面两个不同的例子中回答你的问题
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));
IDE(Eclipse)的输出
命令行输出:
注意:"确定"是我的System.out.println我放入Run1.jar(我用大写字母保存文件jar,但你可以使用你的名字)
答案 1 :(得分:0)
我添加到您的问题中的错误与缺少的参数相关:args[0]
,第9行抛出ArrayIndexOutOfBoundsException
。
论证" 1"没有传递给run1.jar
异常堆栈显示了jar-in-jar加载器的用法,为什么?
使用Oracle命令行实用程序或ANT构建jar并再次测试。