-1

I want to create directories automatically on my SDCard with given path which contains complete path for a file. the path is coming dynamically from a server so I don't know what are the names of the directories are and how many deep is the directory structure is.

e.g. dir1/dir2/dir3/file1.txt

I am using the following piece of code

createDirectoryIfNotPresent(Environment.getExternalStorageDirectory() + "/"+ mypaths.getNextPath());

where definition of

createDirectoryIfNotPresent

is

private void createDirectoryIfNotPresent(String fileName) {
    File f = new File(fileName);

    if(!f.exists())
        f.mkdirs();
}

but the above code creates directory for file1.txt as well. How do I avoid this? I just want to create directories for directory names and not for filenames.

halfer
  • 18,701
  • 13
  • 79
  • 158
Nik
  • 2,561
  • 6
  • 36
  • 59

1 Answers1

1

You can do something as simple as check if the filename contains .txt or other extensions

if(f.toString.contains(".txt")) {
f.createNewFile();
} else {
f.mkdirs();
}

If the extensions keep changing, you might even resort to using regular expressions.

Royston Pinto
  • 6,543
  • 2
  • 26
  • 46
  • I dont even know the extension of the file. – Nik Sep 24 '12 at 11:16
  • Ok, so basically any file has to be in the format name.extension You can use regular expression to see if the input name matches it. If yes, create a file, else go for a Directory. Refer this link for more info on regex http://www.vogella.com/articles/JavaRegularExpressions/article.html – Royston Pinto Sep 24 '12 at 11:25