2010-08-04 6 views
25

두 파일의 diff를 만들고 싶습니다. Java에서 코드를 검색해 보았습니다. 그러나이를 위해 간단한 코드/유틸리티 코드를 찾지 못했습니다. 따라서 필자는 어떻게 든 내 Java 코드에서 linux diff/sdiff 명령을 실행하여 diff를 저장 한 파일을 반환하면 위대 할 것이라고 생각했습니다.Java 코드에서 Linux 명령을 실행하는 방법은 무엇입니까?

fileA와 fileB의 두 파일이 있다고 가정합니다. 내 Java 코드를 통해 fileDiff라는 파일에 diff를 저장할 수 있어야합니다. 그런 다음 fileDiff에서 데이터를 가져 오는 것은별로 중요하지 않습니다.

+0

http://www.javaworld.com/javaworld/jw-12-2000/jw-1229-traps를 읽으십시오. html –

답변

10

당신은 세번째 파일은 diff를 저장하고 다음에 읽을 필요가없는 대신에 당신이 Runtime.exec

Process p = Runtime.getRuntime().exec("diff fileA fileB");                                      
BufferedReader stdInput = new BufferedReader(new InputStreamReader(p.getInputStream())); 
while ((s = stdInput.readLine()) != null) { 
     System.out.println(s); 
} 
33

java.lang.Runtime.exec을 사용하면 간단한 코드를 실행할 수 있습니다. 이렇게하면 Process이 다시 제공되며 출력을 디스크에 임시 저장하지 않고도 표준 출력을 직접 읽을 수 있습니다. 그것은 출력, 컴파일 할 때

import java.io.BufferedReader; 
import java.io.InputStreamReader; 

public class testprog { 
    public static void main(String args[]) { 
     String s; 
     Process p; 
     try { 
      p = Runtime.getRuntime().exec("ls -aF"); 
      BufferedReader br = new BufferedReader(
       new InputStreamReader(p.getInputStream())); 
      while ((s = br.readLine()) != null) 
       System.out.println("line: " + s); 
      p.waitFor(); 
      System.out.println ("exit: " + p.exitValue()); 
      p.destroy(); 
     } catch (Exception e) {} 
    } 
} 

실행 :

는 예를 들어, 다음을 수행하는 방법을 소개하는 전체 프로그램의

line: ./ 
line: ../ 
line: .classpath* 
line: .project* 
line: bin/ 
line: src/ 
exit: 0 

예상대로.

프로세스 표준 오류에 대해서는 error stream, 프로세스 표준 입력에 대해서는 output stream을 혼동받을 수 있습니다. 이 문맥에서, 입/출력은 입력이 이기 때문에 반전되고,에서이 프로세스로 처리됩니다 (즉, 프로세스의 표준 출력).

실제 명령에서 2>&1을 사용하는 것과 달리 Java에서 프로세스 표준 출력과 오류를 병합하려면 ProcessBuilder을 조사해야합니다.

+0

답장을 보내 주셔서 감사합니다. – chitresh

4
Runtime run = Runtime.getRuntime(); 
//The best possible I found is to construct a command which you want to execute 
//as a string and use that in exec. If the batch file takes command line arguments 
//the command can be constructed a array of strings and pass the array as input to 
//the exec method. The command can also be passed externally as input to the method. 

Process p = null; 
String cmd = "ls"; 
try { 
    p = run.exec(cmd); 

    p.getErrorStream(); 
    p.waitFor(); 

} 
catch (IOException e) { 
    e.printStackTrace(); 
    System.out.println("ERROR.RUNNING.CMD"); 

}finally{ 
    p.destroy(); 
} 
12

또한 쉘 스크립트 파일을 작성하고 Java 코드에서 해당 파일을 호출 할 수도 있습니다. 아래 그림과 같이

{ 
    Process proc = Runtime.getRuntime().exec("./your_script.sh");       
    proc.waitFor(); 
} 

실행이 끝나면 스크립트 파일에서 linux 명령을 작성하면 Java에서 diff 파일을 읽을 수 있습니다.

이 접근법의 장점은 Java 코드를 변경하지 않고 명령을 변경할 수 있다는 것입니다.

4

unix4j을 사용해보세요. 그것은 리눅스 명령을 실행하는 자바 라이브러리에 관한 것입니다. 예를 들면 다음과 같은 명령어가 있다면 : cat test.txt | grep "Tuesday"| sed "s/kg/kg/g"| 이 프로그램의 정렬은 Unix4j.cat ("test.txt"). grep ("Tuesday"). sed ("s/kg/kg/g")가됩니다.종류();

1

try { 
     //chm file address 
     String chmFile = System.getProperty("user.dir") + "/chm/sample.chm"; 
     Desktop.getDesktop().open(new File(chmFile)); 
    } catch (IOException ex) { 
     Logger.getLogger(Frame.class.getName()).log(Level.SEVERE, null, ex); 
     { 
      JOptionPane.showMessageDialog(null, "Terjadi Kesalahan", "Error", JOptionPane.WARNING_MESSAGE); 
     } 
    } 
0

의 구멍 당신이 호출 할 수있는 경우 런타임은 모두 윈도우리눅스에 대한 자바에서 명령.

import java.io.*; 

public class Test{ 
    public static void main(String[] args) 
    { 
      try 
      { 
      Process process = Runtime.getRuntime().exec("pwd"); // for Linux 
      //Process process = Runtime.getRuntime().exec("cmd /c dir"); //for Windows 

      process.waitFor(); 
      BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream())); 
      String line; 
       while ((line=reader.readLine())!=null) 
       { 
       System.out.println(line); 
       } 
      }  
       catch(Exception e) 
      { 
       System.out.println(e); 
      } 
      finally 
      { 
       process.destroy(); 
      } 
    } 
} 

는 도움이되기를 바랍니다 .. :)

0

제안 된 솔루션을 commons.io를 사용하여 최적화 될 수를, 오류 스트림을 처리하고 예외를 사용하여. Java 8 이상에서 사용할 수 있도록 다음과 같이 랩핑 할 것을 제안합니다.

public static List<String> execute(final String command) throws ExecutionFailedException, InterruptedException, IOException { 
    try { 
     return execute(command, 0, null, false); 
    } catch (ExecutionTimeoutException e) { return null; } /* Impossible case! */ 
} 

public static List<String> execute(final String command, final long timeout, final TimeUnit timeUnit) throws ExecutionFailedException, ExecutionTimeoutException, InterruptedException, IOException { 
    return execute(command, 0, null, true); 
} 

public static List<String> execute(final String command, final long timeout, final TimeUnit timeUnit, boolean destroyOnTimeout) throws ExecutionFailedException, ExecutionTimeoutException, InterruptedException, IOException { 
    Process process = new ProcessBuilder().command("bash", "-c", command).start(); 
    if(timeUnit != null) { 
     if(process.waitFor(timeout, timeUnit)) { 
      if(process.exitValue() == 0) { 
       return IOUtils.readLines(process.getInputStream(), StandardCharsets.UTF_8); 
      } else { 
       throw new ExecutionFailedException("Execution failed: " + command, process.exitValue(), IOUtils.readLines(process.getInputStream(), StandardCharsets.UTF_8)); 
      } 
     } else { 
      if(destroyOnTimeout) process.destroy(); 
      throw new ExecutionTimeoutException("Execution timed out: " + command); 
     } 
    } else { 
     if(process.waitFor() == 0) { 
      return IOUtils.readLines(process.getInputStream(), StandardCharsets.UTF_8); 
     } else { 
      throw new ExecutionFailedException("Execution failed: " + command, process.exitValue(), IOUtils.readLines(process.getInputStream(), StandardCharsets.UTF_8)); 
     } 
    } 
} 

public static class ExecutionFailedException extends Exception { 

    private static final long serialVersionUID = 1951044996696304510L; 

    private final int exitCode; 
    private final List<String> errorOutput; 

    public ExecutionFailedException(final String message, final int exitCode, final List<String> errorOutput) { 
     super(message); 
     this.exitCode = exitCode; 
     this.errorOutput = errorOutput; 
    } 

    public int getExitCode() { 
     return this.exitCode; 
    } 

    public List<String> getErrorOutput() { 
     return this.errorOutput; 
    } 

} 

public static class ExecutionTimeoutException extends Exception { 

    private static final long serialVersionUID = 4428595769718054862L; 

    public ExecutionTimeoutException(final String message) { 
     super(message); 
    } 

} 
관련 문제