繁体   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