首页 > 解决方案 > 将交互式 shell 输出转换为纯文本

问题描述

我正在尝试使用 Java 在我的 Linux 机器上查看我的 CPU 的温度表。这段代码将显示其他命令的 shell 输出,ls, cat file,但不会显示watch sensors,因为它返回交互式输出。有没有办法可以以某种方式将其转换为纯文本?

Error: [/usr/bin/watch, sensors]

Error opening terminal: unknown.

import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;

public class tempapp{

public static void main (String args[]) throws IOException, InterruptedException {
    //build command
    List<String> commands = new ArrayList<String>();
    commands.add("/usr/bin/watch");
    //args
    commands.add("sensors");
    System.out.println(commands);

    ProcessBuilder pb = new ProcessBuilder(commands);
    pb.directory(new File("/home/ethano"));
    pb.redirectErrorStream(true);
    Process process = pb.start();

    //Read output
    StringBuilder out = new StringBuilder();
    BufferedReader br = new BufferedReader(new InputStreamReader(process.getInputStream()));
    String line = null, previous = null;
    while ((line = br.readLine()) != null)
        if (!line.equals(previous)) {
            previous = line;
            out.append(line).append('\n');
            System.out.println(line);
        }

    //Check result
    if (process.waitFor() == 0){
        System.out.println("\n success");
        System.exit(0);
    }

    //weird termination
    System.err.println(commands);
    System.err.println(out.toString());
    System.exit(1);
    }
}

标签: javalinuxshellcommand-line

解决方案


所做的只是每两秒watch调用一次给出的命令(在这种情况下)。你可以简单地让你的应用程序通过每两秒sensors调用一次 for 循环来模拟这种行为(或者你需要多少次),因此不需要读取交互式 shell 输出。/usr/bin/sensors


推荐阅读