首页 > 解决方案 > 为什么我的 ProcessBuilder inputStream 产生的数据与来自 linux 命令行的数据不同

问题描述

当我从 Ubuntu 18.4 命令行运行以下命令时:

sudo ./nuvgpio 47 1 > gpioresult-47.txt

生成的文件具有以下数据:

Try 4E
ChipID_Hi=0xD2, ChipID_Lo=0x82.
2, GP48, data=0x00

当我从 Java 运行该过程时,结果流不包含最后一行。

import java.io.*;

/**
 * Run a command  line program (nuvgpio) to read/write the status of GPIO pins on a Jetway SBC.
 */
public class JetwayIODriver {

    private static int LED_PIN_NUMBER = 40;
    private static int COVER_PIN_NUMBER = 42;

    public static void main(String args[]) throws InterruptedException {

        try {
            String directoryStr = "/home/tester2/IdeaProjects/automation-framework/device-common-parent/device-io/src/";
            File dir = new File(directoryStr);

            ProcessBuilder builder = new ProcessBuilder();
            builder.directory(dir);
            builder.redirectErrorStream();
            int mode = 1;   // 1=read, 0=write
            builder.command("/bin/bash", "-c", "echo 'tester2' | sudo -S ./nuvgpio", Integer.toString(COVER_PIN_NUMBER), Integer.toString(mode));

            Process process = builder.start();
            InputStreamReader input = new InputStreamReader(process.getInputStream());
            BufferedReader reader = new BufferedReader(input);

            String line;
            while ((line = reader.readLine()) != null) {
                System.out.println ("Stdout: " + line);
            }

            int exitCode = process.waitFor();
            input.close();
            System.out.println(String.format("GPIO process finished with exit code : %s", exitCode));

        } catch (FileNotFoundException fnf) {
            System.out.println(fnf.getMessage());
        } catch (Throwable t) {
            System.out.println(t.getMessage());
        }
    }
}

Java的输出:

Stdout: Try 4E
Stdout: ChipID_Hi=0xD2, ChipID_Lo=0x82.
GPIO process finished with exit code : 0

需要注意的一件奇怪的事情:当我从命令行运行并输出到控制台时,第三行文本与新提示位于同一行: 在此处输入图像描述

nuvgpio 程序似乎没有在末尾放置换行符。这可能是原因吗?如果是这样,我可以在流程输出中注入一个吗?

标签: javashellprocessbuilder

解决方案


推荐阅读