gpt4 book ai didi

Java 通过传递参数从另一个 jar 运行 jar

转载 作者:塔克拉玛干 更新时间:2023-11-02 19:49:52 25 4
gpt4 key购买 nike

我已经生成了 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)

最佳答案

我们在这里,下面是两个不同的例子来回答你的问题

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) 的输出

enter image description here

命令行输出:

enter image description here

注意:“ok”是我放入 Run1.jar 中的 System.out.println(我用大写字母保存了文件 jar,但你可以使用你自己的名字)

关于Java 通过传递参数从另一个 jar 运行 jar,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45435665/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com