Search code examples
kotlincmdprocessbuilder

How can I run a bat file with spaces in the filepath?


I want to run a bat file used to compile sass to css from within a Kotlin program, on a Windows machine. I had everything working using Runtime.exec until I switched to a Windows account that had a space in the username. From what I read, I read that using ProcessBuilder would make this easier. It seems that even with ProcessBuilder I still can't get it to work, no matter what I try.

Here is my code so far

val commands = mutableListOf(
                "cmd",
                "/c",
                "C:\\Users\\John Doe\\VCS\\test\\tools\\sass\\windows\\dart-sass\\sass.bat",
                "--no-source-map",
                "C:\\Users\\John Doe\\VCS\\test\\src\\main\\sass\\global.scss",
                "global.css"
        )

val processBuilder = ProcessBuilder(commands)
val process = processBuilder.start()

...

The error I get is 'C:\Users\John' is not recognized as an internal or external command, operable program or batch file. It doesn't help if I surround the strings that have spaces with \".


Solution

  • This is actually a Windows cmd issue. The question here shows that in cmd, in addition to quoting the file paths, you also have to quote the entire part of the command line text after the /c switch.

    I don't know if this is the best way to do it in ProcessBuilder, but I was able to get it to work with the following code.

    "cmd.exe",
                    "/c",
                    "\"\"C:/Users/John Doe/VCS/test/tools/sass/windows/dart-sass/sass.bat\" "
                    + "--no-source-map "
                    + "\"C:/Users/John Doe/VCS/test/src/main/sass/global.scss\" "
                    + "\"global.css\"\""