2010-03-05 1 views
0

diff 실행에서 얻은 데이터를 Java 프로그램의 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 모두 파일을 가리키는 파일 객체 비교하기 : 아래

내가 지금까지 가지고있는 코드입니다. 힌트

답변

1

그냥 몇 가지, 당신은 할 수 :

  • 파이프 직접 그렙에 DIFF의 출력 :
  • diff -n leftpath rightPath | grep "^a" 대신 표준 입력의 GREP에서 출력 파일을 읽어 grep "^a" tmpFile
  • 사용 ProcessBuilder 취득하는 귀하의 Process을 사용하여 stderr을 읽지 않아 쉽게 차단 프로세스를 피할 수 있습니다. redirectErrorStream