有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

尝试在另一个目录中运行Bat文件时发生Java IOException

我正在使用ApacheCommonsExec在我指定的目录中运行一个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
`

这对我来说毫无意义,因为文件名似乎与目录中的文件对齐,但process builder找不到它


共 (1) 个答案

  1. # 1 楼答案

    问题是,您没有从"C:\Users\Aaron\Documents\MinecraftForge\forge\mcp"运行程序,因此y命令行无法找到参数指定的文件。所以你应该尝试通过绝对路径

    或者,稍微修改一下代码:

    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();
            }
        }
    }