将数据写入java中调用的grep程序的InputStream

时间:2010-03-05 08:00:47

标签: java process exec inputstream outputstream

我正在尝试将从一系列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对象。

1 个答案:

答案 0 :(得分:1)

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

  • 将diff的输出直接传递给grep:diff -n leftpath rightPath | grep "^a"
  • 从grep而不是stdin:grep "^a" tmpFile
  • 读取输出文件
  • 使用ProcessBuilder让您的Process轻松避免阻止过程,因为您没有使用redirectErrorStream
  • 来阅读stderr