[英]Java Runtime.exec fail with space in linux
我搜索了很多,但沒有找到解決方案。 我的目標是使用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]#
誰能解釋原因並給出解決方法?
exec
有兩個版本。
在這里,您可以通過與在命令行上執行命令類似的方式來指定命令,即,您需要用空格將引號引起來。
cmd /c dir "C:\\Program Files"
在這里,您分別指定參數,因此參數按原樣給出,即不帶引號。 exec
方法將處理參數中的所有空格和引號字符,並根據需要正確引用和轉義參數以執行命令。
cmd /c dir C:\\Program Files
因此,刪除添加的多余引號:
if (isWindows()) {
commandArray = new String[] { "cmd", "/c", "dir", "C:\\Program Files"};
} else {
commandArray = new String[] { "ls", "/root/a directory with space"};
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.