如何使用Java代码在Java包内运行批处理文件?
我需要运行一个批处理文件,它已经在我的Java包中了。下面是我的代码如何使用Java代码在Java包内运行批处理文件?,java,batch-file,command-line,runtime.exec,Java,Batch File,Command Line,Runtime.exec,我需要运行一个批处理文件,它已经在我的Java包中了。下面是我的代码 public class ScheduleTest { /** * @param args the command line arguments */ public static void main(String[] args) throws IOException { Process exec = Runtime.getRuntime().exec("test.bat")
public class ScheduleTest {
/**
* @param args the command line arguments
*/
public static void main(String[] args) throws IOException {
Process exec = Runtime.getRuntime().exec("test.bat");
}
}
test.bat位于scheduletest
包中,scheduletest
类也位于该包中。下面是包结构
我怎样才能做到这一点
编辑
这是我的批处理文件的内容
echo hello;
pause
通常,当IDE编译源代码时,
test.bat
应该放在包含二进制文件的文件夹中,保留相同的包结构,例如bin/scheduletest/test.bat
。假设这样,您可以使用类加载器加载批处理文件:
ClassLoader loader = ScheduleTest.class.getClassLoader();
URL resource = loader.getResource("scheduletest/test.bat");
Process exec = Runtime.getRuntime().exec(resource.getPath());
要读取进程的输出,您需要获取其输入流:
InputStream inputStream = exec.getInputStream();
BufferedReader br = new BufferedReader(new InputStreamReader(inputStream));
String line = null;
while((line = br.readLine()) != null) {
System.out.println(line);
}
不过最好有一个资源目录,因为自动构建过程(如Ant或Maven)会在清理时删除此文件。除非您确实需要将批处理文件放在java源代码文件夹中,否则我会将其上移到项目的根目录,或者更好,创建/resources文件夹并将其放在那里
然后,您可以让IDE或生成系统将其复制到您的
bin
/生成。您现有的代码可以正常运行。我不会将其直接放入IDE的二进制文件中,因为您可能会发现清理项目也会自动删除批处理文件。您需要的是IDE或生成系统将其复制到bin
,作为生成过程的一部分。谢谢。成功了。但是,它没有向我显示任何批处理文件。即使我给了它完整的批处理文件路径,它也发生了。我已经用批处理文件的内容更新了我的问题。@只是因为您没有从流程的输出流中读取。看看我最新的答案。姚是最好的。谢谢