[英]Java getRuntime Exec
Am calling ap = Runtime.getRuntime().exec(command) on Java 1.8. 我在Java 1.8上调用ap = Runtime.getRuntime()。exec(command)。 The command calls a bash script as follows:
该命令调用bash脚本,如下所示:
#!/bin/bash
args=("$@")
cat /home/user/Downloads/bigtext.txt | grep ${args[0]}
The above bash script works fine when called with the command line. 使用命令行调用时,上面的bash脚本工作正常。 When called within my Java application using exec() I get no CAT output back.
使用exec()在我的Java应用程序中调用时,我没有收到CAT输出。 it does not seem to get past p.waitFor();
它似乎没有通过p.waitFor(); Where am I going wrong?
我哪里错了?
If I run a command directly such as "ls -alF" every thing works as expected. 如果我直接运行命令,例如“ls -alF”,那么每件事都按预期工作。
$ java -version java version "1.8.0_31" Java(TM) SE Runtime Environment (build 1.8.0_31-b13) Java HotSpot(TM) 64-Bit Server VM (build 25.31-b07, mixed mode)
String tmp = "/home/user/search "+input;
System.out.println(tmp); // /home/user/search sometextarg
String woa = executeCommand(tmp);
private String executeCommand(String command) {
StringBuilder output = new StringBuilder();
BufferedReader reader = null;
Process p;
try {
p = Runtime.getRuntime().exec(command);
p.waitFor();
reader = new BufferedReader(new InputStreamReader(p.getInputStream()));
String line = "";
while ((line = reader.readLine())!= null) {
output.append(line + "\n");
}
} catch (Exception e) {
e.printStackTrace();
}
return output.toString();
}
Your Java process and your script are deadlocked waiting on each other: you are waiting for the process to exit, the process is waiting for you to read the output. 您的Java进程和脚本在等待彼此的死锁:您正在等待进程退出,进程正在等待您读取输出。
It happens to work for ls -alF
and other commands with small outputs because they all fit in the pipe's buffer (64kib on my system). 它恰好适用于
ls -alF
和其他具有小输出的命令,因为它们都适合管道缓冲区(我系统上的64kib)。
Just move the p.waitFor()
below the while loop, and you'll have more luck: 只需将while循环下面的
p.waitFor()
移动,你就会有更多的运气:
private String executeCommand(String command) {
StringBuilder output = new StringBuilder();
BufferedReader reader = null;
Process p;
try {
p = Runtime.getRuntime().exec(command);
reader = new BufferedReader(new InputStreamReader(p.getInputStream()));
String line = "";
while ((line = reader.readLine())!= null) {
output.append(line + "\n");
}
p.waitFor();
} catch (Exception e) {
e.printStackTrace();
}
return output.toString();
}
If you additionally want this to work correctly with values containing spaces and certain other characters, you have to: 如果您还希望使用包含空格和某些其他字符的值正常工作,则必须:
"${args[0]}"
in your script. "${args[0]}"
。 executeCommand
to use Runtime.exec(String[])
instead of Runtime.exec(String)
. executeCommand
以使用Runtime.exec(String[])
而不是Runtime.exec(String)
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.