I am writing a small Java Application and I am having problems with a filepath.
I want to execute a batch file with
Runtime.getRuntime().exec("cmd /c start c:\program files\folder\file.bat");
But now Java cries because of the whitespace in the filepath.
How can I escape it?
EDIT:
Ok, thank you for the answers guys. But I just ran into a new problem:
If I start the .bat this way it just opens a cmd window and nothing happens. But if I move the .bat into c:/folder/ without spaces it works...the .bat itself is fine too.
In case you want to run powershell.exe -File from the command line, you always have to set paths with spaces in double quotes (""). Also try using the Grave Accent Character (`) PowerShell uses the grave accent (`) character as its escape character. Just add it before each space in the file name.
In a bash script, we can escape spaces with \ .
The solutions are to use quotes or the backslash escape character. The escape character is more convenient for single spaces, and quotes are better when there are multiple spaces in a path. You should not mix escaping and quotes.
There is no legitimate reason to avoid spaces. All modern file systems handle file names with spaces just fine.
You can avoid any problems like this by using the Runtime#exec that takes a String[]:
Runtime.getRuntime().exec(new String[] {"cmd", "/c", "start", "c:\\program files\\folder\\file.bat"});
That way you don't have to worry about quoting the file names. However, you still have to worry about quoting \ in the file names.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With