论坛首页 入门技术论坛

java调用系统命令

浏览 2000 次
精华帖 (0) :: 良好帖 (0) :: 新手帖 (0) :: 隐藏帖 (0)
作者 正文
   发表时间:2009-08-13  

简单的静态函数

SysCmd.java:

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();
    }
}

 
 

 

论坛首页 入门技术版

跳转论坛:
Global site tag (gtag.js) - Google Analytics