java调用批处理命令

java调用批处理命令:

  1. windows中的.bat和.cmd文件。
  2. linux中的sh文件。

java实例demo:

String cmd = "E:\\Test\\hello.cmd";
Process process = null;
InputStream fis = null;
InputStreamReader isr = null;
BufferedReader br = null;

try {
   process = Runtime.getRuntime().exec(cmd);
   fis = process.getInputStream();
   isr = new InputStreamReader(fis);
   br = new BufferedReader(isr);
   String line = null;
   while ((line = br.readLine()) != null) {
      System.out.println(line);
   }
} catch (IOException e) {
   e.printStackTrace();
} finally {
   try {
      if (br!=null){
         br.close();
      }
      if (isr!=null) {
         isr.close();
      }
      if (fis!=null) {
         fis.close();
      }

   } catch (IOException e) {
      e.printStackTrace();
   }
}

if (process != null) {
   process.destroy();
}

Runtime.getRuntime().exec(String command, String[] envp, File dir)参数详解:

command:命令参数数组

envp:环境变量设置,格式name=value,可以设置为null。

dir:子进程的工作目录,可以设置为null。

发布了31 篇原创文章 · 获赞 1 · 访问量 1171

猜你喜欢

转载自blog.csdn.net/quietbxj/article/details/103672407