当前位置: 移动技术网 > IT编程>开发语言>Java > java执行Linux命令的方法

java执行Linux命令的方法

2019年07月22日  | 移动技术网IT编程  | 我要评论

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

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网