我进行了很多搜索,但没有找到解决方案。我的目标是使用Java调用命令并在Windows和Linux中获取输出。我找到Runtime.exec
方法并做了一些实验。一切正常,除非命令参数中有空格。测试代码如下,同样在github中。
该代码在Windows上运行良好,但是在linux中,输出为空:
import java.io.BufferedReader;
import java.io.InputStreamReader;
public class Main {
public static void main(String[] args) {
try {
Runtime rt = Runtime.getRuntime();
String[] commandArray;
if (isWindows()) {
commandArray = new String[]{"cmd", "/c", "dir", "\"C:\\Program Files\""};
} else {
commandArray = new String[]{"ls", "\"/root/a directory with space\""};
}
String cmd = String.join(" ",commandArray);
System.out.println(cmd);
Process process = rt.exec(commandArray);
BufferedReader input = new BufferedReader(
new InputStreamReader(process.getInputStream()));
String result = "";
String line = null;
while ((line = input.readLine()) != null) {
result += line;
}
process.waitFor();
System.out.println(result);
} catch (Exception e) {
System.out.println(e.getMessage());
}
}
public static boolean isWindows() {
String OS = System.getProperty("os.name").toLowerCase();
return (OS.indexOf("win") >= 0);
}
}
如果我直接在bash中执行打印的命令,则输出是预期的。
[root@localhost javatest]# javac Main.java
[root@localhost javatest]# java Main
ls "/root/a directory with space"
[root@localhost javatest]# ls "/root/a directory with space"
a.txt b.txt
[root@localhost javatest]#
谁能解释原因并给出解决方法?
郎朗坤
相关分类