java調用cmd命令

package mypackage;

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

public class SysCmd
{

    public static String autoExec(String cmdLine) throws IOException, InterruptedException
    {
        if (System.getProperty("os.name").matches(".*[Ww]indows.*"))
        {
            return exec(new String[] { "cmd", "/c", cmdLine });
        }
        else
        {
            return exec(new String[] { "sh", "-c", cmdLine });
        }
    }

    public static String exec(String[] cmdArray) throws IOException, InterruptedException
    {
        Process p = Runtime.getRuntime().exec(cmdArray);

        String line = null;
        StringBuffer result = new StringBuffer();

        BufferedReader brIn = new BufferedReader(new InputStreamReader(p.getInputStream()));
        while ((line = brIn.readLine()) != null)
        {
            result.append(line + "/n");
        }
        brIn.close();

        BufferedReader brErr = new BufferedReader(new InputStreamReader(p.getErrorStream()));
        while ((line = brErr.readLine()) != null)
        {
            result.append(line + "/n");
        }
        brErr.close();

        return result.toString();
    }
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章