第七色在线视频,2021少妇久久久久久久久久,亚洲欧洲精品成人久久av18,亚洲国产精品特色大片观看完整版,孙宇晨将参加特朗普的晚宴

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

Java Runtime.exec在Linux中空間不足時失敗

Java Runtime.exec在Linux中空間不足時失敗

函數(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。

  • exec(String command)

    在這里,您可以通過與在命令行上執(zhí)行命令類似的方式來指定命令,即,您需要用引號將參數(shù)引起來。

    cmd /c dir "C:\Program Files"
  • exec(String[] cmdarray)

    在這里,您分別指定參數(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"};

}


查看完整回答
反對 回復(fù) 2021-05-12
  • 1 回答
  • 0 關(guān)注
  • 289 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯(lián)系客服咨詢優(yōu)惠詳情

幫助反饋 APP下載

慕課網(wǎng)APP
您的移動學(xué)習(xí)伙伴

公眾號

掃描二維碼
關(guān)注慕課網(wǎng)微信公眾號