java中批处理原理_如何从Java应用程序运行批处理文件?

问题

在我的Java应用程序中,我想运行一个名为"scons -Q implicit-deps-changed build\file_load_type export\file_load_type"的批处理文件

好像我甚至无法让我的批处理文件执行。我没有想法。

这就是我在Java中所拥有的:

Runtime.

getRuntime().

exec("build.bat", null, new File("."));

以前,我有一个我想要运行的Python Sconscript文件,但由于这不起作用,我决定通过批处理文件调用该脚本,但该方法尚未成功。

#1 热门回答(160 赞)

批处理文件不是可执行文件。他们需要一个应用程序来运行它们(即cmd)。

在UNIX上,脚本文件在文件的开头有shebang(#!)以指定执行它的程序。双击Windows是由Windows资源管理器执行的.CreateProcess对此一无所知。

Runtime.

getRuntime().

exec("cmd /c start \"\" build.bat");

注意:使用start \"\"命令,将打开一个单独的命令窗口,其中包含空白标题,批处理文件中的任何输出都将显示在那里。它也应该只使用`cmd / c build.bat",在这种情况下,如果需要,可以从Java中的子进程读取输出。

#2 热门回答(20 赞)

有时线程执行进程时间高于JVM线程等待进程时间,它会在你调用的进程需要一些时间进行处理时发生,请使用waitFor()命令,如下所示:

try{

Process p = Runtime.getRuntime().exec("file location here, don't forget using / instead of \\ to make it interoperable");

p.waitFor();

}catch( IOException ex ){

//Validate the case the file can't be accesed (not enought permissions)

}catch( InterruptedException ex ){

//Validate the case the process is being stopped by some external situation

}

这样,JVM将停止,直到你正在调用的进程在继续执行线程执行堆栈之前完成。

#3 热门回答(18 赞)

Runtime runtime = Runtime.getRuntime();

try {

Process p1 = runtime.exec("cmd /c start D:\\temp\\a.bat");

InputStream is = p1.getInputStream();

int i = 0;

while( (i = is.read() ) != -1) {

System.out.print((char)i);

}

} catch(IOException ioException) {

System.out.println(ioException.getMessage() );

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值