ProcessBuilder的简单使用

使用ProcessBuilder执行简单的linux命令 【ProcessBuilder的简单使用】demo代码:

public static void testProcessBuilder(String command){ boolean err =false; try { //初始化ProcessBuilder对象 Process p=new ProcessBuilder(command.split(" ")).start(); //用于存储执行命令的结果 BufferedReader results=new BufferedReader(new InputStreamReader(p.getInputStream())); String s; while((s=results.readLine())!=null){ System.out.println(s); } //用于存储执行命令的错误信息 BufferedReader errors=new BufferedReader(new InputStreamReader(p.getErrorStream())); while((s=errors.readLine())!=null){ System.err.println(s); err=true; } } catch (Exception e) { e.printStackTrace(); } if(err){ throw new RuntimeException("Error executing "+command); } }

command参数的值为要执行的命令,如查看java版本号
public static void main(String[] args) { String command="java -version"; testProcessBuilder(command); }

    推荐阅读