简体   繁体   English

有没有一种方法可以简化我编写的终端类或使其更有效:) thnks

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

To run the terminal from my intelliJ I wrote next code: 为了从我的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;

    }

If there is a way to simplify this :) 如果有一种方法可以简化:)

I would first look into correctness here; 我首先在这里研究正确性 that one line: 那一行:

           return line;

looks suspicious. 看起来可疑。 Or, more precisely: are you sure that your command will always print exactly one line? 或者,更准确的说:你确定你的命令总是准确地打印一行 Because you are returning after reading the first line; 因为您阅读完第一行后将返回; and thus omitting any other output. 因此省去了其他任何输出。

Besides: you should change your code to use try-with resources instead - your return statement just leaves your readers unclosed. 此外:您应该更改代码以使用try-with资源代替-您的return语句只会使您的读者处于关闭状态。 Probably not a problem here because all of that should go away when the process object goes away, but still: bad practice. 这里可能不是问题,因为当流程对象消失时,所有这些都应该消失,但仍然是:不好的做法。 "Cleanup things" before exiting your methods! 退出方法之前,请先“清理事物”!

To answer the actual question: after looking into these conceptual things I am pointing out, there isn't much else you could do. 要回答一个实际的问题:在研究了我指出的这些概念性内容之后,您无能为力了。 Probably use a ProcessBuilder instead of the somehow "outdated" Runtime.exec() call. 可能使用ProcessBuilder而不是以某种方式“过时”的Runtime.exec()调用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM