java process调用可执行文件,windows 或者 linux

最近项目中看到有需要在java程序中调用其他三方工具(如程序中调用三方转码工具)的需求,于是process便在这个需求中崭露头角:

(一下只简述用法,不透露实际应用)

1.调用windows平台的.bat

a.在F:盘下 新建a.txt 编辑内容为“love code”;

新建cmd.bat,编辑内容“notepad F:\a.txt”

b.在java程序中写如下调用语句

[html]view plaincopyprint?

  1. CommandUtil.exec("cmd /c start F://cmd.bat");

CommandUtil的exec方法如下:

[html]view plaincopyprint?

  1. public static boolean exec(String command) throws IOException, InterruptedException{
  2. log.info("执行脚本:"+command);
  3. Process process = Runtime.getRuntime().exec(command);
  4. int exitValue = process.waitFor();
  5. if (process != null) {
  6. process.destroy();
  7. }
  8. if (exitValue!=0){
  9. return false;
  10. }
  11. return true;
  12. }

c.在windows平台下运行程序,变可以打开记事本,看到“love code”字样;

2.调用linux平台下的.sh脚本

用法一样,只是把bat文件换成linux下的shell脚本文件,并用相同代码调用 。

在linux平台下运行程序即可调用shell脚本。