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

标签 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对象,指向要比较的文件。

最佳答案

只需一些提示,您就可以:

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

关于java - 将数据写入java中调用的grep程序的InputStream,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2385304/

相关文章:

c - 在使用 exec 运行另一组进程之前等待并行进程

sql - 将临时表传递给 EXEC sp_executesql

bash - shell脚本中的多个exec

java - 错误: appengine-maven-plugin:1. 3.2:运行失败:非零退出:1

Java 常量字符串在 Android 中被损坏

java - 解决Maven依赖收敛问题

android - 获取正在运行的进程列表并终止特定进程

java - 线程从生成线程继承锁

c++ - 在 Qt/C++ 中获取 QProcess 的可执行文件名称

java - 从 Java 程序运行批处理文件,然后运行 ​​exe 文件