簡體   English   中英

有沒有一種方法可以簡化我編寫的終端類或使其更有效:) thnks

[英]is there a way to simplify this terminal class I wrote or make it more efficient :) thnks

為了從我的IntelliJ運行終端,我編寫了下一個代碼:

public static String runTerminalCommand (String command){

        Process proc = null;
        try {
            proc = Runtime.getRuntime().exec(command);
        } catch (IOException e) {
            e.printStackTrace();
        }

        // Read the output

        BufferedReader reader =
                new BufferedReader(new InputStreamReader(proc.getInputStream()));

        String line = "";
        try {
            while((line = reader.readLine()) != null) {
                out.print(line + "\n");
                return line;
            }
        } catch (IOException e) {
            e.printStackTrace();
        }

        try {
            proc.waitFor();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        return null;

    }

如果有一種方法可以簡化:)

我首先在這里研究正確性 那一行:

           return line;

看起來可疑。 或者,更准確的說:你確定你的命令總是准確地打印一行 因為您閱讀完第一行后將返回; 因此省去了其他任何輸出。

此外:您應該更改代碼以使用try-with資源代替-您的return語句只會使您的讀者處於關閉狀態。 這里可能不是問題,因為當流程對象消失時,所有這些都應該消失,但仍然是:不好的做法。 退出方法之前,請先“清理事物”!

要回答一個實際的問題:在研究了我指出的這些概念性內容之后,您無能為力了。 可能使用ProcessBuilder而不是以某種方式“過時”的Runtime.exec()調用。

暫無
暫無

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

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