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

JAVA执行LINUX命令
public static void main(String[] args) throws Exception {
        Process proc = Runtime.getRuntime().exec("/bin/bash", null, new File("/bin"));
        BufferedReader in = new BufferedReader(new InputStreamReader(proc.getInputStream()));
        PrintWriter out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(proc.getOutputStream())), true);
        out.println("cd");
        out.println("ls");
        out.println("pwd");
        out.println("exit");
        String line;
        while ((line = in.readLine()) != null) 
                System.out.println(line);
        proc.waitFor();
        in.close();
        out.close();
        proc.destroy();
}

注:/bin/bash 必须先执行,等同于#!/bin/bash的命令

PrintWriter构造时候添加参数true的作用是每次println都会刷新缓存区域。无需手动out.flush();