如何在Java中运行Linux命令?

时间:2010-08-04 06:50:02

标签: java runtime.exec

我想创建两个文件的差异。我尝试在Java中搜索代码,但没有找到任何简单的代码/实用程序代码。因此,我想如果我能以某种方式从我的java代码运行linux diff / sdiff命令并使它返回一个存储差异的文件,那么它会很棒。

假设有两个文件fileA和fileB。我应该能够通过我的java代码将他们的diff存储在一个名为fileDiff的文件中。然后从fileDiff获取数据将没什么大不了的。

10 个答案:

答案 0 :(得分:44)

您可以使用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,令人困惑。在这种情况下,输入和输出是相反的,因为它是进程输入到该进程(即进程的标准输出)。

如果要从Java合并流程标准输出和错误(而不是在实际命令中使用2>&1),则应该查看ProcessBuilder

答案 1 :(得分:23)

答案 2 :(得分:15)

您还可以编写shell脚本文件并从java代码中调用该文件。如下图所示

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

将linux命令写入脚本文件中,一旦执行完毕,就可以用Java读取diff文件。

这种方法的优点是你可以在不改变java代码的情况下改变命令。

答案 3 :(得分:12)

您无需将差异存储在第3个文件中,然后从中读取。相反,您可以使用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);
}

答案 4 :(得分:5)

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

答案 5 :(得分:5)

尝试使用unix4j。它是关于java中运行linux命令的库。例如,如果你有一个像这样的命令: cat test.txt | grep“星期二”| sed“s / kilogram / kg / g”|分类 在这个程序将成为: Unix4j.cat( “test.txt的”)的grep( “星期二”)的sed( “S /千克/千克/克”)排序(); ...

答案 6 :(得分:2)

您可以从java为 Windows 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();
             }  
    }
}

希望它能帮助...... :)

答案 7 :(得分:1)

如果在Windows中打开

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

答案 8 :(得分:1)

可以使用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);
    }

}

答案 9 :(得分:0)

Java函数带来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;
}