2010-08-04 23 views
25

Tôi muốn tạo khác biệt của hai tệp. Tôi đã cố gắng tìm kiếm mã trong Java mà nó, nhưng didnt tìm thấy bất kỳ mã đơn giản/tiện ích cho việc này. Do đó, tôi nghĩ nếu tôi bằng cách nào đó có thể chạy linux diff/sdiff lệnh từ mã java của tôi và làm cho nó trở lại một tập tin lưu trữ các diff sau đó nó sẽ là tuyệt vời.Làm thế nào để chạy các lệnh linux trong mã java?

Giả sử có hai tệp làA và tệpB. Tôi sẽ có thể lưu trữ diff của họ trong một tập tin gọi là fileDiff thông qua mã java của tôi. Sau đó, lấy dữ liệu từ fileDiff sẽ không có vấn đề lớn.

+0

Hãy nhớ đọc: http://www.javaworld.com/javaworld/jw-12-2000/jw-1229-traps. html –

Trả lời

10

Bạn không cần phải lưu trữ các diff trong một file thứ 3 và sau đó đọc từ trong Thay vào đó bạn tận dụng các 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

Bạn có thể sử dụng java.lang.Runtime.exec để chạy mã đơn giản. Điều này mang lại cho bạn một số Process và bạn có thể đọc trực tiếp đầu ra tiêu chuẩn của mình mà không phải lưu trữ tạm thời đầu ra trên đĩa.

Ví dụ, đây là một chương trình hoàn chỉnh sẽ giới thiệu làm thế nào để làm điều đó:

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

Khi biên soạn và chạy, nó sẽ tạo ra:

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

như mong đợi.

Bạn cũng có thể nhận được mã số error stream cho lỗi tiêu chuẩn quy trình và output stream cho đầu vào tiêu chuẩn quy trình, đủ gây nhầm lẫn. Trong ngữ cảnh này, đầu vào và đầu ra được đảo ngược vì nó nhập từ quy trình này (tức là, tiêu chuẩn đầu ra của quy trình).

Nếu bạn muốn hợp nhất đầu ra tiêu chuẩn quy trình và lỗi từ Java (trái ngược với việc sử dụng 2>&1 trong lệnh thực tế), bạn nên xem xét ProcessBuilder.

+0

Cảm ơn tất cả các câu trả lời của bạn. – 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

Bạn cũng có thể viết tệp tập lệnh shell và gọi tệp đó từ mã java. như được hiển thị bên dưới

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

Viết lệnh linux trong tệp tập lệnh, khi thực thi kết thúc, bạn có thể đọc tệp khác trong Java.

Lợi thế của phương pháp này là bạn có thể thay đổi các lệnh bằng cách thay đổi mã java.

4

cố gắng sử dụng unix4j. nó về một thư viện trong java để chạy lệnh linux. ví dụ nếu bạn có một lệnh như: cat test.txt | grep "Thứ ba" | sed "s/kg/kg/g" | sắp xếp trong chương trình này sẽ trở thành: Unix4j.cat ("test.txt"). grep ("Thứ ba"). sed ("s/kilogram/kg/g").sắp xếp();

1

nếu mở trong cửa sổ

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

Bạn có thể gọi thời gian chạy lệnh từ java cho cả của WindowsLinux.

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

Hy vọng nó sẽ giúp .. :)

0

Các giải pháp đề nghị có thể được tối ưu hóa sử dụng commons.io, xử lý các dòng lỗi, và sử dụng ngoại lệ. Tôi khuyên bạn nên bọc như thế này để sử dụng trong Java 8 trở lên:

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

} 
Các vấn đề liên quan