0

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.

Ahmed Ashour
  • 5,179
  • 10
  • 35
  • 56
user987316
  • 894
  • 4
  • 13
  • 35

6 Answers6

3

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";
JoGe
  • 872
  • 10
  • 26
2

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.

Daniel
  • 4,033
  • 4
  • 24
  • 33
0

You need to escape path seprator:

String folderName = "D:\\my folder path\\ActualFolderName";

File file = new File(folderName);
if (!file.exists()) {
    file.mkdirs();
}
Ahmed Ashour
  • 5,179
  • 10
  • 35
  • 56
AsSiDe
  • 1,826
  • 2
  • 15
  • 24
  • 2
    FYI: the `file.exists()` check is unnecessary, as `mkdirs()` will only create the directory if it doesn't already exist. – Jonas Czech Jan 08 '16 at 13:05
0

Following alternatives should work in Windows:

String folderName = "d:\\my\\ folder\\ path\\ActualFolderName";
String folderName = "\"d:\\my folder path\\ActualFolderName\"";
Mario
  • 1,661
  • 13
  • 22
0

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();
Boon
  • 1,073
  • 1
  • 16
  • 42
0

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.

Community
  • 1
  • 1
Jonas Czech
  • 12,018
  • 6
  • 44
  • 65