函數(shù)式編程
2021-05-03 17:14:00
我進行了很多搜索,但沒有找到解決方案。我的目標(biāo)是使用Java調(diào)用命令并在Windows和Linux中獲取輸出。我找到Runtime.exec方法并做了一些實驗。一切正常,除非命令參數(shù)中有空格。測試代碼如下,同樣在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中執(zhí)行打印的命令,則輸出是預(yù)期的。[root@localhost javatest]# javac Main.java [root@localhost javatest]# java Mainls "/root/a directory with space"[root@localhost javatest]# ls "/root/a directory with space"a.txt b.txt[root@localhost javatest]# 誰能解釋原因并給出解決方法?
1 回答

郎朗坤
TA貢獻1921條經(jīng)驗 獲得超9個贊
有兩個版本exec
。
在這里,您可以通過與在命令行上執(zhí)行命令類似的方式來指定命令,即,您需要用引號將參數(shù)引起來。
cmd /c dir "C:\Program Files"
在這里,您分別指定參數(shù),因此參數(shù)按原樣給出,即不帶引號。該
exec
方法將處理參數(shù)中的所有空格和引號字符,并根據(jù)需要正確引用和轉(zhuǎn)義參數(shù)以執(zhí)行命令。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"};
}
添加回答
舉報
0/150
提交
取消