java启动另一个jar并向其提供输入
我需要启动jar并为其提供输入。 我发现了如何使用Runtime#getRuntime#exec启动jar,它可以毫无问题地工作,我也发现了这一点
String command = "stop";
BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(process.getOutputStream()));
bufferedWriter.write(String.format("%s\n", command));
bufferedWriter.flush();
我应该做这项工作。但问题是,它对我不起作用,它实际上什么都不起作用。有人知道怎么做吗? 过程:
public static Process startJar(File jarFile, String flags, String args, @Nullable File dir) throws IOException {
if (dir == null){
return Runtime.getRuntime().exec(String.format("cmd /c start /wait \"\" java -jar %s \"%s\" %s",flags ,jarFile.getAbsolutePath(), args));
}
return Runtime.getRuntime().exec(String.format("cmd /c start /wait \"\" java -jar %s \"%s\" %s", flags, jarFile.getAbsolutePath(), args), null, dir);
}
# 1 楼答案
如果输入是命令行args,则直接将其传递给
exec
如果不是,并且假设
process
是正在运行的另一个jar,则需要写入process
的InputStream,而不是OutputStreamprocess.getOutputStream()
将为您提供process
正在向其输出结果的流,而不是从其读取输入的位置编辑:在Taschi指出代码正确后
我发现another question和你的相似。公认的答案是,您必须关闭
writer
或传递\n
才能使其工作。试试看。如果它仍然无法工作,请确保正在运行的另一个JAR正在等待其STDIN上的输入# 2 楼答案
问题是,我在一个新窗口(cmd/cstart)中启动了这个jar,删除它之后,一切都正常工作