Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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/ without spaces it works...the .bat itself is fine too.

like image 740
tk2000 Avatar asked Sep 29 '11 10:09

tk2000


People also ask

How do you escape space in file path?

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.

How do I escape a space in bash?

In a bash script, we can escape spaces with \ .

How do you escape a space in Terminal?

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.

Can you have spaces in file paths?

There is no legitimate reason to avoid spaces. All modern file systems handle file names with spaces just fine.


1 Answers

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.

like image 67
Matthew Farwell Avatar answered Sep 23 '22 07:09

Matthew Farwell