使用 `Runtime.getRuntime().exec()` 从 `top` 获取输出

Using `Runtime.getRuntime().exec()` to get the output from `top`

我想要 运行 使用 Runtime.getRuntime().exec(String) 方法的 top -n 1 命令,并将 top -n 1 的输出输入到我的 Java 程序中。

我尝试了使用 BufferedReader 获取进程输出并使用返回的进程 InputStream 的标准方法,但未返回任何数据。

我也尝试了以下...

        String path = "/home/user/Desktop/";
        String cmd = "#!/bin/sh\ntop -n 1 > " + path + "output";
        File shellCmd = new File(path + "topscript.sh");
        PrintWriter writer = new PrintWriter(shellCmd);
        writer.write(cmd);
        writer.flush();
        Runtime.getRuntime().exec("chmod +x " + shellCmd.getAbsolutePath()); 
        Runtime.getRuntime().exec(shellCmd.getAbsolutePath());

创建 shell script 和输出,但输出为空。但是,如果我随后加载上面代码生成的 local shell 和 运行 script,我会在输出文件中得到正确的输出。

What's going wrong?
    String cmd = "#!/bin/sh\ntop -n1 -b > " + path + "output";
    File shellCmd = new File(path + "topscript.sh");
    PrintWriter writer = new PrintWriter(shellCmd);
    writer.write(cmd);
    writer.flush();
    Runtime.getRuntime().exec("chmod +x " + shellCmd.getAbsolutePath());

    ProcessBuilder pb = new ProcessBuilder(shellCmd.getAbsolutePath());
    Map<String, String> enviornments = pb.environment();
    enviornments.put("TERM", "xterm-256color");
    Process process = pb.start();

    BufferedReader inputStreamReader = new BufferedReader(new InputStreamReader(process.getInputStream()));
    BufferedReader errorStreamReader = new BufferedReader(new InputStreamReader(process.getErrorStream()));
    String str = inputStreamReader.readLine();
    System.out.println(str);
    System.out.println(errorStreamReader.readLine());

使用 ProcessBuilder 并设置 TERM变量。

如果想重定向 top 到文件。需要添加 -b 选项以避免 error: initializing curses.