Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/321.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何在java中从类路径执行.bat?_Java_Batch File - Fatal编程技术网

如何在java中从类路径执行.bat?

如何在java中从类路径执行.bat?,java,batch-file,Java,Batch File,如何从类路径执行.bat?我只能执行.bat特定目录,如D:\temp\kill chrome.bat 类路径目录 + src + -> .java files .... + resource + kill-chrome.bat 我的程序不起作用 String path = "cmd /c start /resource/kill-chrome.bat"; Runtime rn = Runtime.getRuntime(); try { Process pr =

如何从
类路径执行
.bat
?我只能执行
.bat
特定目录,如
D:\temp\kill chrome.bat

类路径目录

+ src
    + -> .java files ....
+ resource
    + kill-chrome.bat 
我的程序不起作用

String path = "cmd /c start /resource/kill-chrome.bat";
Runtime rn = Runtime.getRuntime();
try {
    Process pr = rn.exec(path);
} catch (IOException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
}  

我得到了最简单的方法,就是使用
file.getAbsolutePath()
方法。我不确定哪种方法合适

String realPath = new File("resource/kill-chrome.bat").getAbsolutePath();
String path = "cmd /c start " + realPath;
Runtime rn = Runtime.getRuntime();
try {
    Process pr = rn.exec(path);
} catch (IOException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
}

runtime.exec(command)
中,无法直接访问
类路径

我认为在类路径中获取文件路径的正确方法如下:

URI uri = YourClass.class.getResource("resource/kill-chrome.bat").toURI();
String path = new File(uri).getAbsolutePath();
此aproach将来自您的工作目录(这可能有所不同):


谢谢,我同意你的看法。另一个主题是基于应用程序本质的文件加载策略,如web应用程序。
new File("resource/kill-chrome.bat").getAbsolutePath();