我正在尝试处理从运行 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/