deles 发表于 2018-8-28 13:01:25

java程序中调用dos shell命令 -- 此处以调用dos命令为例

/**  
*Java调用windows的DOS命令
  
*/
  
public class RunDocInJava{
  
    public static void main(String[] args) {
  
      InputStream ins = null;
  
      String[] cmd = new String[] { "cmd.exe", "/c", "ipconfig" };// 命令行
  
      try {
  
      //Runtime.exec()用来执行外部程序或命令
  
         Process process = Runtime.getRuntime().exec(cmd);
  
         ins = process.getInputStream();// 获取执行doc命令后的信息
  
            //将获取的信息尽可能放入缓冲区
  
            BufferedReader reader = new BufferedReader(new InputStreamReader(ins));
  
            String line = null;
  
            //读取信息
  
            //会先读取缓冲区信息,如果信息不完全才会去读取源数据
  
            while ((line = reader.readLine()) != null) {
  
                System.out.println(line);
  
            }
  
            int exitVal = process.waitFor(); //获取程序返回值   成功为“0”
  
            System.out.println("return Integer:"+exitVal);
  
            process.getOutputStream().close();//程序中如果没有关闭会造成堆栈溢出
  
      } catch (Exception e) {
  
            e.printStackTrace();
  
      }
  
    }
  
}


页: [1]
查看完整版本: java程序中调用dos shell命令 -- 此处以调用dos命令为例