Escape whitespace in filepath
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/ wit开发者_开发技巧hout spaces it works...the .bat itself is fine too.
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.
Runtime.getRuntime().exec("cmd /c start \"c:/program files/folder/file.bat\"");
should work
Instead of using Runtime.getRuntime it is better to use ProcessBuilder
That way you can have something like:
List<String> command = new ArrayList<String>();
command.add("first-arg");
command.add("second arg with spaces") //this one will be accepted as a single argument, eventhough it has spaces
A solution for windows 7 at least:
Runtime.getRuntime().exec("my_program_name.exe \"" + namefile+"\");
The idea is to put namefile between the character ".
I think it cries because of the unescaped back slashes in your string. Quote the file name.
Put quotes around and quote backslashes:
Runtime.getRuntime().exec("cmd /c start \"c:\\program files\\folder\\file.bat\"");
surround the filepath with "
Runtime.getRuntime().exec("cmd /c start \"c:\\program files\\folder\\file.bat\"");
and properly escape the \
in the path as well
you have to escape the slashes so \\
and in windows white space are escaped with %20
. I don't know about other system, could work. But first thing do the \\
.
精彩评论