JAVA 调用外部程序

1.  如果只是执行而不需要得到返回结果

String shell="command line";  

String command="command line";
  try {
   Runtime rt=Runtime.getRuntime();
   rt.exec(command);
  } catch (Exception e) {
   // TODO: handle exception
   e.printStackTrace();
  }


2. 如果需要得到返回结果,可以用Process

Process process;
  StringBuilder sb=new StringBuilder();
  try {
   Runtime rt=Runtime.getRuntime();
   //String shell="command line";
   String[] shell={"command line",args[0]}; //命令可以用数组的方式,这样可以处理参数中的特殊字符,如空格。
   process=rt.exec(shell);
   InputStreamReader reader=new InputStreamReader(process.getInputStream());
   BufferedReader br=new BufferedReader(reader);
   String line;
   while((line=br.readLine())!=null){
    sb.append(line);
   }
   System.out.println(sb);
  } catch (Exception e) {
   // TODO: handle exception
   e.printStackTrace();
  }



猜你喜欢

转载自blog.csdn.net/IamstudyingJava/article/details/25412713