如何处理windows批处理文件路径中的空格



我在windows机器上有一个批处理文件。相同的路径中有空格。例如C:\Hello World\MyFile.bat

我正在尝试通过java执行批处理文件,如下所示:

Runtime.getRuntime().exec(dosCommand + destinationFilePath + batch)

但是,由于路径有空格,它表示"C:\Hello"不是有效的命令或目录。

我也试过这个:

完整命令:cmd /c start /wait "C:/Hello World/MyFile.bat"它打开命令提示符,但不转到文件夹Hello World,也不执行bat文件

我该如何处理这种情况。如果有其他信息,请告诉我。是必需的。

使用引号("C:Hello WorldMyFile.bat")就可以了。在Java中,您必须用String batch = ""C:Hello WorldMyFile.bat"")对引号进行割线。

我能够使用ProcessBuilder解决它。bat文件所在的目录可以添加到工作目录中,如下所示:

processBuilder.directory(新文件("C:\hello-world\"));

这就像宝石一样。

    int result = 1;
    final File batchFile = new File("C:\hello world\MyFile.bat");
    final File outputFile = new File(String.format("C:\hello world\output_%tY%<tm%<td_%<tH%<tM%<tS.txt", System.currentTimeMillis()));
    final ProcessBuilder processBuilder = new ProcessBuilder(batchFile.getAbsolutePath());
    processBuilder.redirectErrorStream(true);
    processBuilder.redirectOutput(outputFile);
    processBuilder.directory(new File("C:\hello world\"));
    try {
        final Process process = processBuilder.start();
        if (process.waitFor() == 0) {
            result = 0;
        }
        System.out.println("Processed finished with status: " + result);
    } catch (IOException | InterruptedException e) {
        e.printStackTrace();
    }

是否尝试转义路径周围的引号,例如:

Runtime.getRuntime().exec(dosCommand + """ + destinationFilePath + batch + """)

我刚用ProcessBuilder解决了这个问题,但我给了processBuilder.directory一个空间的目录,并用bat文件名运行了命令。

ProcessBuilder pb = new ProcessBuilder("cmd", "/c", "start", "/wait", "export.bat");
    pb.directory(new File(batDirectoryWithSpace));
    pb.redirectError();
    try {
        Process process = pb.start();
        System.out.println("Exited with " + process.waitFor());
    } 
    catch (IOException | InterruptedException ex) {
        Exceptions.printStackTrace(ex);
    }

相关内容

最新更新