Reputation: 942
I have my java code like below-
string folderName = "d:\my folder path\ActualFolderName";
File folder = new File( folderName );
folder.mkdirs();
So here as given directory path has space in it. folder created is d:\my
, not the one I am expecting.
Is there any special way to handle space in file/folder paths.
Upvotes: 0
Views: 11854
Reputation: 1153
First of all, the String path you have is incorrect anyway as the backslash must be escaped with another backslash, otherwise \m
is interpreted as a special character.
How about using a file URI?
String folderName = "d:\\my folder path\\ActualFolderName";
URI folderUri = new URI("file:///" + folderName.replaceAll(" ", "%20"));
File folder = new File(folderUri);
folder.mkdirs();
Upvotes: 0
Reputation: 1846
You need to escape path seprator:
String folderName = "D:\\my folder path\\ActualFolderName";
File file = new File(folderName);
if (!file.exists()) {
file.mkdirs();
}
Upvotes: 0
Reputation: 12328
You need to escape your path (use \\
in your path instead of \
) and you also need to use String
, with an uppercase S, as the code you posted does not compile. Try this instead, which should work:
String folderName = "D:\\my folder path\\ActualFolderName";
new File(folderName).mkdirs();
If you are getting your folder name from user input (ie.not hardcoded in your code), you don't need to escape, but you should ensure that it is really what you expect it is (print it out in your code before creating the File to verify).
If your are still having problems, you might want to try using the system file separator character, which you can get with System.getProperty(file.separator)
or accesing the equivalent field in the File
class. Also check this question.
Upvotes: 0
Reputation: 4211
Unless you are running a really old version of Java, use the Path API from JDK7:
Path p = Paths.get("d:", "my folder path", "ActualFolderName");
File f = p.toFile();
It will take care of file separators and spaces for you automatically, regardless of OS.
Upvotes: 2
Reputation: 910
You should us \\
for path in java. Try this code
String folderName = "D:\\my folder path\\ActualFolderName";
File folder = new File( folderName );
folder.mkdirs();
Or use front-slashes /
so your application will be OS independent.
String folderName = "D:/my folder path1/ActualFolderName";
Upvotes: 3
Reputation: 1781
Following alternatives should work in Windows:
String folderName = "d:\\my\\ folder\\ path\\ActualFolderName";
String folderName = "\"d:\\my folder path\\ActualFolderName\"";
Upvotes: 0