Runtime.getRuntime().exec中命令含有括号问题

来源:互联网 发布:网络用语dm是什么意思 编辑:程序博客网 时间:2024/06/06 02:56

在写批量执行bat工具的时候,想起了之前写的定时小工具里面的执行方法。

使用Runtime.getRuntime().exec方法。

Runtime.getRuntime().exec("cmd /c start c:/test.bat") 
这样就可以像dos窗口直接执行命令行一样。


getRuntime返回Runtime的实例化对象,exec方法是返回Process对象。


查看Process类可以发现:

The ProcessBuilder.start() and Runtime.exec methods create a native process and return an instance of a subclass of Process that can be used to control the process and obtain information about it. The class Process provides methods for performing input from the process, performing output to the process, waiting for the process to complete, checking the exit status of the process, and destroying (killing) the process. 

The methods that create processes may not work well for special processes on certain native platforms, such as native windowing processes, daemon processes, Win16/DOS processes on Microsoft Windows, or shell scripts.


方法创建了本地进程返回了Process子类的对象,用于控制进程并获取信息。Process类提供从进程输入,进程输出,进程等待结束和进程退出状态还有销毁(杀死)进程的方法。创建进程的方法对于本地平台的特殊进程可能无法较好地工作。如本地窗口进程,守护进程,微软Windows下的Win16/DOS 进程或shell脚本。


先在c盘写一个简单的test.bat。

echo aaaapause

然后是用java进行调用:

import java.io.IOException;public class TestRuntime {public static void main(String[] args) {try {Runtime.getRuntime().exec("cmd /c start c:\\test.bat");} catch (IOException e) {// TODO Auto-generated catch block\System.out.println("file not found");}}}

这样是正常执行的。



但是问题来了,当bat文件有括号的时候,执行就会不一样了,将原有的test.bat改为test(s).bat后执行。



后面看到了这篇博客,http://blog.sina.com.cn/s/blog_656977f40101d05p.html

但是博客里面也有错误,文件路径应该使用\\或者/。

Runtime.getRuntime().exec("cmd /c start call \"c:\\test(s).bat\"");

这样之后正常访问,call正常调用了带括号bat文件。


其实这个问题纠结了我很久,确实有些命令并不能很好的工作,一直就在解决这个问题。但是我还好找到了这个问题的解决方案,不然只会在这个问题上越陷越深,其实当一个问题快到死角的时候,要从换种思路解决问题,


原来的思路:

现在问题是无法识别文件名带有括号的bat文件——》如何让exec方法识别到。


新思路:

现在问题是无法识别文件名带有括号的bat文件——》能不能去掉bat文件名中的括号。


其实这个思路是由这位仁兄的博客里想到的:

http://blog.csdn.net/xulianboblog/article/details/18360131

不一样的解决问题的思路。


还有:http://blog.163.com/jackswu@yeah/blog/static/1406291232012575743301/ 写到的一些命令,比较有用。


java的Runtime.getRuntime().exec(commandText)可以调用执行cmd指令。 

cmd /c dir 是执行完dir命令后关闭命令窗口。 

cmd /k dir 是执行完dir命令后不关闭命令窗口。 

cmd /c start dir 会打开一个新窗口后执行dir指令,原窗口会关闭。 

cmd /k start dir 会打开一个新窗口后执行dir指令,原窗口不会关闭。 
:增加了start,就会打开新窗口,可以用cmd /?查看帮助信息。



0 0
原创粉丝点击