2

我正在使用 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
`

这对我来说毫无意义,因为文件名似乎与目录中的文件对齐,但流程构建器找不到它。

4

1 回答 1

2

问题是,您没有从那运行程序"C:\Users\Aaron\Documents\MinecraftForge\forge\mcp"y 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();
        }
    }
}
于 2013-07-31T23:47:22.373 回答