【问题标题】:Writing data to InputStream of grep program invoked in java将数据写入java中调用的grep程序的InputStream
【发布时间】:2011-01-24 00:37:38
【问题描述】:

我正在尝试将运行 diff 获得的数据处理为 java 程序中的 GNU grep 实例。我已经设法使用 Process 对象的 outputStream 获得 diff 的输出,但我目前正在让程序将此数据发送到 grep 的标准输入(通过在 Java 中创建的另一个 Process 对象)。使用输入运行 Grep 仅返回状态码 1。我做错了什么?

下面是我目前的代码:

public class TestDiff {
final static String diffpath = "/usr/bin/";

public static void diffFiles(File leftFile, File rightFile) {

    Runtime runtime = Runtime.getRuntime();

    File tmp = File.createTempFile("dnc_uemo_", null);

    String leftPath = leftFile.getCanonicalPath();
    String rightPath = rightFile.getCanonicalPath();

    Process proc = runtime.exec(diffpath+"diff -n "+leftPath+" "+rightPath, null);
    InputStream inStream = proc.getInputStream();
    try {
        proc.waitFor();
    } catch (InterruptedException ex) {

    }

    byte[] buf = new byte[256];

    OutputStream tmpOutStream = new FileOutputStream(tmp);

    int numbytes = 0;
    while ((numbytes = inStream.read(buf, 0, 256)) != -1) {
        tmpOutStream.write(buf, 0, numbytes);
    }

    String tmps = new String(buf,"US-ASCII");

    inStream.close();
    tmpOutStream.close();

    FileInputStream tmpInputStream = new FileInputStream(tmp);

    Process addProc = runtime.exec(diffpath+"grep \"^a\" -", null);
    OutputStream addProcOutStream = addProc.getOutputStream();

    numbytes = 0;
    while ((numbytes = tmpInputStream.read(buf, 0, 256)) != -1) {
        addProcOutStream.write(buf, 0, numbytes);
        addProcOutStream.flush();
    }
    tmpInputStream.close();
    addProcOutStream.close();

    try {
        addProc.waitFor();
    } catch (InterruptedException ex) {

    }

    int exitcode = addProc.exitValue();
    System.out.println(exitcode);

    inStream = addProc.getInputStream();
    InputStreamReader sr = new InputStreamReader(inStream);
    BufferedReader br = new BufferedReader(sr);

    String line = null;
    int numInsertions = 0;
    while ((line = br.readLine()) != null) {

        String[] p = line.split(" ");
        numInsertions += Integer.parseInt(p[1]);

    }
    br.close();
}
}

leftPath 和 rightPath 都是 File 对象,指向要比较的文件。

【问题讨论】:

    标签: java process exec inputstream outputstream


    【解决方案1】:

    只需几个提示,您就可以:

    • 将 diff 的输出直接通过管道传输到 grep:diff -n leftpath rightPath | grep "^a"
    • 从 grep 而不是 stdin 读取输出文件:grep "^a" tmpFile
    • 使用ProcessBuilder 获取Process,您可以轻松避免阻塞进程,因为您没有使用redirectErrorStream 读取stderr

    【讨论】:

      猜你喜欢
      • 2013-09-25
      • 1970-01-01
      • 2016-03-19
      • 1970-01-01
      • 1970-01-01
      • 2012-04-25
      • 2016-02-01
      • 2014-05-05
      • 2021-11-28
      相关资源
      最近更新 更多