java执行Linux命令的方法

前端技术 2023/09/09 Java

本文实例讲述了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();
        }
}

本文地址:https://www.stayed.cn/item/25873

转载请注明出处。

本站部分内容来源于网络,如侵犯到您的权益,请 联系我

我的博客

人生若只如初见,何事秋风悲画扇。