java执行shell命令

java

浏览数:212

2019-1-8

AD:资源代下载服务

片段 1片段 2


ShellCommand.java

import java.io.IOException;

public class ShellCommand
{
    public static void execCmd(String cmd)
    {
        execCmd(cmd, null);
    }
    
    public static void execCmd(String cmd, StringBuffer sb)
    {
        Process process = null;
        try {
            process = Runtime.getRuntime().exec(cmd);
            getProcessOutput(process, sb);
        } catch (Exception e) {
            if (sb != null) {
                sb.append("executeCmd: " + cmd + "\n");
                sb.append("errorMessage: " + e.toString() + "\n");
            }
        }
        if (process != null) {
            try {
                process.waitFor();
                process.getOutputStream().close();
                process.getErrorStream().close();
                process.getInputStream().close();
            } catch (InterruptedException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
    
    private static void getProcessOutput(Process process, StringBuffer sb)
    {
        if (process == null) {
            return;
        }
        StreamCaptureThread errorStream = new StreamCaptureThread(process.getErrorStream());
        StreamCaptureThread inputStream = new StreamCaptureThread(process.getInputStream());
        errorStream.setOutput(sb);
        inputStream.setOutput(sb);
        new Thread(errorStream).start();
        new Thread(inputStream).start();
    }
}


StreamCaptureThread.java

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

public class StreamCaptureThread implements Runnable
{
    InputStream m_in;
    StringBuffer m_sb;

    public StreamCaptureThread(InputStream inputStream)
    {
        this.m_in = inputStream;
    }

    public void setOutput(StringBuffer sb)
    {
        m_sb = sb;
    }

    public void run()
    {
        try {
            BufferedReader br = new BufferedReader(new InputStreamReader(m_in));
            String line = null;
            while (m_in != null && (line = br.readLine()) != null) {
                if (line.trim().length() > 0) {
                    if (m_sb != null) {
                        m_sb.append(line);
                        m_sb.append("\n");
                    }
                }
            }
        } catch (IOException ex) {
            ex.printStackTrace(System.err);
        }
    }
}