在寫批量運行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 aaaa pause
然后是用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
不一樣的解決這個問題的思路。