日期:2014-05-16  浏览次数:20709 次

Java调用Linux命令-实例
public class LinuxCommand
{
    /**
     * @param args
     * @throws IOException
     */
    public static void main(String[] args) throws IOException
    {
        //命令行;
        String[] cmd = {"chmod","-R","775",args[0]};
        //调用getRuntime().exec产生一个本地进程,并返回一个Process子类实例;
        Process process = Runtime.getRuntime().exec(cmd);
        //输出命令结果;
        System.out.println(loadSteam(process.getInputStream()));
        //输出错误信息;
        System.err.println(loadSteam(process.getErrorStream()));
    }
    
    //读取流;
    private static String loadSteam(InputStream inputStream) throws IOException
    {
        InputStreamReader inputStreamReader = new InputStreamReader(inputStream);
        StringBuffer sb = new StringBuffer();
        BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
        String line = null;
        while ((line = bufferedReader.readLine()) != null)
        {
            sb.append(line);
        }
        return sb.toString();
    }
}

?

?

?