欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

java执行Linux命令的方法

程序员文章站 2024-02-29 21:00:10
本文实例讲述了java执行linux命令的方法。分享给大家供大家参考。具体实现方法如下: 复制代码 代码如下: public class streamgobbler e...

本文实例讲述了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程序设计有所帮助。