java执行Linux命令的方法

本文实例讲述了java执行Linux命令的方法。分享给大家供大家参考。具体实现方法如下:

复制代码 代码如下:

public class StreamGobbler extends Thread { 
     
    InputStream is; 
    String type; 
 
    public StreamGobbler(InputStream is, String type) { 
        this.is = is; 
        this.type = type; 
    } 
 
    public void run() { 
        try { 
            InputStreamReader isr = new InputStreamReader(is); 
            BufferedReader br = new BufferedReader(isr); 
            String line = null; 
            while ((line = br.readLine()) != null) { 
                if (type.equals("Error")) { 
                    System.out.println("Error   :" + line); 
                } else { 
                    System.out.println("Debug:" + line); 
                } 
            } 
        } catch (IOException ioe) { 
            ioe.printStackTrace(); 
        } 
    } 

private void shell(String cmd)
{
        String[] cmds = { "/bin/sh", "-c", cmd };
        Process process;

        try
        {
            process = Runtime.getRuntime().exec(cmds);

            StreamGobbler errorGobbler = new StreamGobbler(process.getErrorStream(), "Error");
            StreamGobbler outputGobbler = new StreamGobbler(process.getInputStream(), "Output");
            errorGobbler.start();
            outputGobbler.start();
            try
            {
                process.waitFor();
            }
            catch (InterruptedException e)
            {
                e.printStackTrace();
            }
        }
        catch (IOException e)
        {
            e.printStackTrace();
        }
}

其中参数 cmd 为Linux命令。每次只能执行一条命令。

1.Java Runtime.exec()注意事项:

① 永远要在调用waitFor()方法之前读取数据流
② 永远要先从标准错误流中读取,然后再读取标准输出流

2.最好的执行系统命令的方法就是写个bat文件或是shell脚本。

希望本文所述对大家的Java程序设计有所帮助。

你可能感兴趣的:(java执行Linux命令的方法)