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

将数据写入java中调用的grep程序的InputStream,java,process,exec,inputstream,outputstream,Java,Process,Exec,Inputstream,Outputstream,我正试图在java程序中将从运行diff获得的数据处理为GNU grep实例。我已经设法使用Process对象的outputStream获得了diff的输出,但我目前正在让程序将此数据发送到grep的标准输入(通过Java中创建的另一个Process对象)。使用输入运行Grep只返回状态代码1。我做错了什么 以下是我目前掌握的代码: public class TestDiff { final static String diffpath = "/usr/bin/"; public static

我正试图在java程序中将从运行diff获得的数据处理为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都是指向要比较的文件的文件对象。

只需几点提示,您可以:

  • 将diff的输出直接导入grep:
    diff-n leftpath rightPath|grep“^a”
  • 从grep而不是stdin读取输出文件:
    grep“^a”tmpFile
  • 使用
    ProcessBuilder
    获取
    流程
    ,您可以轻松避免阻塞流程,因为您没有使用
    redirectErrorStream来读取stderr