2010-03-05 31 views
0

我试图在java程序中处理从diff的运行得到的数据到GNU grep的一个实例。我设法使用Process对象的outputStream获取diff的输出,但是我目前正在将程序发送给grep的标准输入(通过另一个用Java创建的Process对象)。使用输入运行Grep只会返回状态码1.我做错了什么?将数据写入java中调用的grep程序的InputStream中

下面是我到目前为止的代码:要比较

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

只是一对夫妇的提示,你可以:

  • 管diff的输出,直接进入的grep:diff -n leftpath rightPath | grep "^a"
  • 从grep的,而不是标准输入读取输出文件:grep "^a" tmpFile
  • 使用ProcessBuilder得到您的Process您可以轻松避免阻止过程,因为您没有通过使用redirectErrorStream
相关问题