簡體   English   中英

如何在 Java 中運行 Linux 命令?

[英]How to run Linux commands in Java?

我想創建兩個文件的差異。 我嘗試在 Java 中搜索執行此操作的代碼,但沒有找到任何簡單的代碼/實用程序代碼。 因此,我想如果我能以某種方式從我的 java 代碼運行 linux diff/sdiff 命令並讓它返回一個存儲差異的文件,那就太好了。

假設有兩個文件fileA 和fileB。 我應該能夠通過我的 java 代碼將它們的差異存儲在一個名為 fileDiff 的文件中。 然后從 fileDiff 獲取數據沒什么大不了的。

您可以使用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

正如預期的那樣。

您還可以獲取流程標准錯誤的錯誤流,以及流程標准輸入的輸出流,這很令人困惑。 在這種情況下,輸入和輸出是相反的,因為它是流程輸入這個流程的(即流程的標准輸出)。

如果您想合並來自 Java 的流程標准輸出和錯誤(而不是在實際命令中使用2>&1 ),您應該查看ProcessBuilder

看一下Runtime.exec()方法: http ://docs.oracle.com/javase/7/docs/api/java/lang/Runtime.html#exec( java.lang.String)

您還可以編寫一個 shell 腳本文件並從 java 代碼調用該文件。 如下所示

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

在腳本文件中寫入 linux 命令,一旦執行結束,您就可以讀取 Java 中的 diff 文件。

這種方法的優點是您可以在不更改 java 代碼的情況下更改命令。

您不需要將差異存儲在第三個文件中,然后從文件中讀取。而是使用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);
}

嘗試使用unix4j 它是關於 java 中的一個庫來運行 linux 命令。 例如,如果你有這樣的命令: cat test.txt | grep "星期二" | sed "s/kg/kg/g" | 在這個程序中排序會變成:Unix4j.cat("test.txt").grep("Tuesday").sed("s/kg/kg/g").sort();

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

您可以從 java 為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();
             }  
    }
}

希望能幫助到你.. :)

建議的解決方案可以使用 commons.io、處理錯誤流和使用 Exceptions 進行優化。 我建議像這樣包裝以便在 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);
    }

}

如果在窗口中打開

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

Java Function 帶來 Linux 命令結果!

public String RunLinuxCommand(String cmd) throws IOException {

    String linuxCommandResult = "";
    Process p = Runtime.getRuntime().exec(cmd);

    BufferedReader stdInput = new BufferedReader(new InputStreamReader(p.getInputStream()));

    BufferedReader stdError = new BufferedReader(new InputStreamReader(p.getErrorStream()));

    try {
        while ((linuxCommandResult = stdInput.readLine()) != null) {

            return linuxCommandResult;
        }
        while ((linuxCommandResult = stdError.readLine()) != null) {
            return "";
        }
    } catch (Exception e) {
        return "";
    }

    return linuxCommandResult;
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM