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


    在写批量运行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

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




  • 相关阅读:
    Java实现 LeetCode 680 验证回文字符串 Ⅱ(暴力)
    Java实现 LeetCode 680 验证回文字符串 Ⅱ(暴力)
    Java实现 LeetCode 680 验证回文字符串 Ⅱ(暴力)
    PHP import_request_variables() 函数
    PHP gettype() 函数
    PHP get_resource_type() 函数
    PHP get_defined_vars() 函数
    PHP floatval()、doubleval () 函数
    反射的相关知识点
    泛型知识
  • 原文地址:https://www.cnblogs.com/bhlsheji/p/5225406.html
Copyright © 2020-2023  润新知