-1

I've made a method that checks 2 strings passed into itself that see's if a root folder and subfolder within it exists and if they don't, create them.

It's easy enough and it works well but my only issue is when I want to check for a root folder only it returns and error since one of the strings is empty.

Is there a smart way of checking for a path like "/data" , "/data/files" or "/data/files/morefiles" to see if all folders exists and if not, create the missing ones?

Roman C
  • 48,723
  • 33
  • 63
  • 158
Dylan Benton
  • 109
  • 1
  • 11
  • Please post the code that you've already wrote. – Grammin Aug 21 '13 at 13:28
  • 1
    possible duplicate of [Create a folder if one doesn't exist](http://stackoverflow.com/questions/14666170/create-a-folder-if-one-doesnt-exist) – Rohit Jain Aug 21 '13 at 13:32
  • possible duplicate of [Is there a proper way to check for file/directory existence in Java?](http://stackoverflow.com/questions/7996524/is-there-a-proper-way-to-check-for-file-directory-existence-in-java) – Math Aug 21 '13 at 13:36

5 Answers5

3

There is a ready-made method which creates all the missing parent directories: File#mkdirs().

Marko Topolnik
  • 188,298
  • 27
  • 302
  • 416
1
new File("/path/to/subdirectory").mkdirs();
gawi
  • 2,634
  • 4
  • 30
  • 43
1

You can use .mkdirs() method on any File object

// Create a directory; all non-existent ancestor directories are
// automatically created
success = (new File("../potentially/long/pathname/without/all/dirs")).mkdirs();
sam_codes
  • 191
  • 6
0

you can take the string and split it using split("\\"); after that, build in a for statement the path, each time checking and creating the folder if needed

String path;// Your path, that you get as parameter
String[] pathArr = path.split("\\");
string str = pathArr[0];
int size = pathArr.size();

for(int i = 1; i <  size ; i++)
{
    // Check and create folder if needed
    str = str + "\\" + pathArr[i];
}
No Idea For Name
  • 11,127
  • 10
  • 38
  • 63
0

You will want to check out the File api. Specifically:

isDirectory()

exists()

mkdirs()

Grammin
  • 11,224
  • 22
  • 76
  • 135