作为我的程序的一部分,我有一个连接管理器,它接收来自客户端的连接,然后为客户端提供用于连接的端口号和密码。此时,管理器需要调用 jar 文件,我必须使用一些参数来处理此连接,然后继续,(忽略其他程序正在执行的操作)。
我的问题是执行 jar 文件。我查找了类似的问题,并尝试使用流程生成器和使用 Runtime.exec。我移动了 jar 文件,并检查了它的权限。它只是拒绝在另一个java程序中工作,但在命令行中工作得很好。这是我的一次测试运行的示例。
package test;
import java.io.*;
public class Main {
public static void main (String [] args ) throws IOException, ClassNotFoundException, InterruptedException {
Process p = Runtime.getRuntime().exec("java -jar \'/home/ryan/CytoscapeInterface.jar" +
"\' arg1 arg2");
//Process builder way
/*ProcessBuilder pb = new ProcessBuilder("/home/ryan/CytoscapeInterface.jar",
"-jar", "CytoscapeInterface.jar", "agr1", "arg2");
pb.redirectErrorStream();
Process p = pb.start();*/
BufferedInputStream bis = new BufferedInputStream(p.getErrorStream());
synchronized (p) { p.waitFor(); }
System.out.println(p.exitValue());//its 1 for runtime, 2 for process Builder
int read = bis.available();
//had a loop, found out I just needed to go through once
byte[] b = new byte [read];
bis.read(b);
read = bis.available();
bis.close();
FileOutputStream fos = new FileOutputStream (new File("/home/ryan/Desktop/FileTest.txt"));
fos.write(b);//Writes error file
fos.close();
}
}
waitFor 对于运行时返回 1,对于构建器返回 2。运行时的错误输出是“无法访问 jarfile '/home/ryan/CytoscapeInterface.jar'。使用构建器时出现几行包含一些奇怪字符的错误,第一个错误是找不到命令。
最佳答案
我已经成功测试了该场景,我可以在java程序中执行jar文件(无需设置类路径)。
您能否确保您已在具有 Main-Class 属性的 jar 中添加了 Manifest 文件。
我的步骤和输出:
- 使用以下行创建了 Mainfest 文件:Main-Class: com.test.TestJSSJar
- 创建测试 Java 程序:
包 com.test;
public class TestJSSJar 扩展了 Object {
公共(public)静态无效主(字符串参数[]){
System.out.println("嗨!我在 jar 里");
System.out.println("参数:"+ args[0]);
}
}
3.打包jar(移至临时文件夹):jar cvfm jss.jar manifest.txt com
4.编写测试程序:
import java.io.BufferedInputStream;
import java.io.IOException;
public class TestJSS extends Object {
static int i = 0;
public static void main(String args[]) throws IOException, InterruptedException {
System.out.println("Calling jar");
Process p = Runtime.getRuntime().exec("java -jar /temp/jss.jar arg1 arg2");
BufferedInputStream bis = new BufferedInputStream(p.getInputStream());
synchronized (p) {
p.waitFor();
}
System.out.println(p.exitValue());
int b=0;
while((b=bis.read()) >0){
System.out.print((char)b);
}
System.out.println("");
System.out.println("Called jar");
}
}
5.输出
Calling jar
0
Hi! I'm in the jar
Arg:arg1
Called jar
关于java - 从另一个 java 程序执行不同的 Jar 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6599290/