2010-08-04 11 views
25

Ich möchte Diff von zwei Dateien erstellen. Ich habe versucht, in Java nach Code zu suchen, der das tut, fand aber dafür keinen einfachen Code/Utility-Code. Daher dachte ich, wenn ich irgendwie Linux diff/sdiff Befehl aus meinem Java-Code ausführen und es eine Datei zurückgeben kann, die das diff speichert, dann wäre es großartig.Wie man Linux-Befehle in Java-Code ausführt?

Angenommen, es gibt zwei Dateien fileA und fileB. Ich sollte in der Lage sein, ihr diff in einer Datei namens fileDiff über meinen Java-Code zu speichern. Dann wäre das Abrufen von Daten aus fileDiff keine große Sache.

+0

Seien Sie sicher, zu lesen: http://www.javaworld.com/javaworld/jw-12-2000/jw-1229-traps. html –

Antwort

10

Sie speichern müssen nicht das Diff in einer dritten Datei und lesen dann aus in Stattdessen Sie nutzen die 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

Sie können java.lang.Runtime.exec verwenden, um einfachen Code auszuführen. Dies gibt Ihnen eine Process zurück und Sie können seine Standardausgabe direkt lesen, ohne die Ausgabe vorübergehend auf der Festplatte speichern zu müssen.

Zum Beispiel, hier ist ein vollständiges Programm, das präsentiert, wie es geht:

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) {} 
    } 
} 

Wenn kompiliert und ausgeführt, gibt sie:

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

wie erwartet.

Sie können auch die error stream für den Prozess Standardfehler und output stream für die Prozess-Standard-Eingabe, zum Verwechseln genug. In diesem Zusammenhang sind die Eingabe und die Ausgabe umgekehrt, da ihr von der Prozess zu diesem ist (d. H. Der Standard Ausgabe des Prozesses).

Wenn Sie die Prozess-Standardausgabe und den Fehler von Java zusammenführen möchten (im Gegensatz zur Verwendung von 2>&1 im eigentlichen Befehl), sollten Sie in ProcessBuilder schauen.

+0

Vielen Dank für Ihre Antworten. – 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

Sie können auch eine Shell-Skriptdatei schreiben und diese Datei aus dem Java-Code aufrufen. wie unten

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

Schreiben Sie die Linux-Befehle in der Skriptdatei, sobald die Ausführung ist über Sie die Diff-Datei in Java lesen kann.

Der Vorteil bei diesem Ansatz ist, dass Sie die Befehle ohne Änderung des Java-Codes ändern können.

4

versuchen, unix4j zu verwenden. Es geht um eine Bibliothek in Java, um den Linux-Befehl auszuführen. zum Beispiel, wenn Sie einen Befehl wie: cat test.txt | Grep "Dienstag" | sed "s/Kilogramm/kg/g" | sort in diesem Programm wird: Unix4j.cat ("test.txt"). grep ("Dienstag"). sed ("s/kg/kg/g").Sortieren();

1

wenn die Öffnung in den Fenstern

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

können Sie rufen Laufzeitbefehle von Java für beide Windows- und Linux.

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(); 
      } 
    } 
} 

Hoffe, es hilft .. :)

0

Die vorgeschlagenen Lösungen optimiert commons.io verwenden könnte, die Fehlerstrom Handhabung und Verwendung von Ausnahmen. Ich würde für die Verwendung so wickeln vorschlagen in Java 8 oder höher:

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); 
    } 

} 
Verwandte Themen