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

How to handle spaces in path to a windows batch file?

我在 windows 机器上有一个批处理文件。 相同的路径中有空格。例如。 C:\你好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 World\MyFile.bat") 应该可以解决问题。在 Java 内,您必须使用 \ (String batch = "\"C:\Hello World\MyFile.bat\"").

来分隔引号

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

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

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

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

这类似于 gem。

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

我刚刚也使用 ProcessBuilder 解决了这个问题,但是我将带有 space 的目录给了 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);
    }