我正在使用Apache Commons Exec在我指定的目录中运行bat文件。
File file = new File("C:\\Users\\Aaron\\Documents\\MinecraftForge\\forge\\mcp");
for(String s : file.list())
{
if(s.equals("recompile.bat"))
{
DefaultExecutor executor = new DefaultExecutor();
executor.setWorkingDirectory(file);
CommandLine commandLine = new CommandLine("recompile.bat");
try
{
executor.execute(commandLine);
} catch (ExecuteException e)
{
e.printStackTrace();
} catch (IOException e)
{
e.printStackTrace();
}
}
}
代码只会尝试运行bat文件,如果它可以找到我正在寻找的文件,但代码会出现
java.io.IOException: Cannot run program "recompile.bat" (in directory "C:\Users\Aaron\Documents\MinecraftForge\forge\mcp"): CreateProcess error=2, The system cannot find the file specified
at java.lang.ProcessBuilder.start(Unknown Source)
at java.lang.Runtime.exec(Unknown Source)
at org.apache.commons.exec.launcher.Java13CommandLauncher.exec(Java13CommandLauncher.java:58)
at org.apache.commons.exec.DefaultExecutor.launch(DefaultExecutor.java:254)
at org.apache.commons.exec.DefaultExecutor.executeInternal(DefaultExecutor.java:319)
at org.apache.commons.exec.DefaultExecutor.execute(DefaultExecutor.java:160)
at org.apache.commons.exec.DefaultExecutor.execute(DefaultExecutor.java:147)
at mod.learncraft.packer.Packager.<init>(Packager.java:24)
at mod.learncraft.packer.Packager.main(Packager.java:38)
Caused by: java.io.IOException: CreateProcess error=2, The system cannot find the file specified
at java.lang.ProcessImpl.create(Native Method)
at java.lang.ProcessImpl.<init>(Unknown Source)
at java.lang.ProcessImpl.start(Unknown Source)
... 9 more
`
这对我来说没有意义,因为文件名似乎与目录中的文件对齐,但是进程构建器找不到它。
答案 0 :(得分:2)
问题是,你没有从"C:\Users\Aaron\Documents\MinecraftForge\forge\mcp"
运行程序,因为CommandLine无法找到参数指定的文件。所以你应该尝试传递绝对路径
或者,稍微修改一下你的代码:
File file = new File("C:\\Users\\Aaron\\Documents\\MinecraftForge\\forge\\mcp");
for(File s : file.listFiles())
{
if(s.getName().equals("recompile.bat"))
{
DefaultExecutor executor = new DefaultExecutor();
executor.setWorkingDirectory(file);
CommandLine commandLine = new CommandLine(s.getAbsolutePath());
try
{
executor.execute(commandLine);
} catch (ExecuteException e)
{
e.printStackTrace();
} catch (IOException e)
{
e.printStackTrace();
}
}
}