簡體   English   中英

使用任何命令行參數對exec調用進行Java IOException

[英]Java IOException on exec call with any command-line arguments

我有一個java應用程序,最終將深入到外部流程集成,包括IPC與這些流程。 但就目前而言,我要做的只是從java運行一個powershell腳本。

我得到了什么:

private void runPowershellScript() {
    String command =
            "" + "powershell" + " ";
//            Paths.get("").toAbsolutePath() + "\\" + scriptFileName + " " +
//            Paths.get("").toAbsolutePath() + "\\" + INPUT_FILE_NAME + " " +
//            Paths.get("").toAbsolutePath() + "\\" + OUTPUT_FILE_NAME + "";

    try {
        ProcessBuilder builder = new ProcessBuilder(command);
        builder.redirectErrorStream(true);
        Process process = builder.start();

        BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(process.getOutputStream()));
        BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()));
        String line;

        while ((line = reader.readLine ()) != null) {
            System.out.println ("Stdout: " + line);
        }

    } catch (IOException e) {
        e.printStackTrace();
    }
}

根據你所看到的,我獲得了Windows Powershell的名稱和版權,但是如果我添加任何注釋掉的行(所有這些行都解析為正確的路徑,例如C:\\Users\\Geoff\\Code\\OPTIP\\FakeProgram.ps1 )我得到: java.io.IOException: Cannot run program "powershell C:\\Users\\Geoff\\Code\\OPTIP\\FakeProgram.ps1 ": CreateProcess error=2, The system cannot find the file specified

我已經嘗試了十幾種不同的強引號和弱引號的組合,我已經嘗試將它們作為參數傳遞給cmd.exe /c powershell ...但是我沒有嘗試過運行腳本。 如果命令字符串中有一個空格,則會出現IO異常。

我想知道它是否與字符編碼有關? 當我簡單地調用powershell時 ,我從' reader.readLine()回來了: W\i\n\ ...我認為這是我的IDE(IntelliJ)的方式告訴我它的“Windows Powershell”每個字母之間的null unicode字符。

Java ProcessBuilder文檔對於您可以作為參數傳遞的內容有點模糊:

一個命令,一個字符串列表,表示要調用的外部程序文件及其參數(如果有)。 哪個字符串列表表示有效的操作系統命令取決於系統。 例如,每個概念參數通常都是此列表中的元素,但是有些操作系統需要程序對命令行字符串本身進行標記 - 在這樣的系統上,Java實現可能需要命令才能包含兩個元素。

我不知道這意味着什么。 我試圖給它的命令可以從CMD和Powershell窗口以及Windows運行對話框中運行。

包含上述方法類的要點: https//gist.github.com/Groostav/9c5913e6f4696a25430d gist包含我的powershell腳本: https//gist.github.com/Groostav/347a283ac7ec6a738191

謝謝你的幫助。

您必須將參數放在單獨的字符串中,而不是將它們作為單個字符串連接到powershell調用。 就像是

new ProcessBuilder("Powershell", scriptFileName,  INPUT_FILE_NAME);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM