Search code examples
javaiocodenameonemkdirs

Recursive directory creation fails on device


My code runs in the simulator, but crashes on Android with a FileNotFoundException as it tries to FileSystemStorage#openOutputStream in an non-existing directory. I create all the needed directories recursively before using

private void ensureParentDirs(String file) {
    final int j = file.lastIndexOf("/");
    final String s = file.substring(0, j);
    if (storage.isDirectory(s)) return;
    storage.mkdir(s);
    if (storage.isDirectory(s)) return;
    ensureParentDirs(s);
    storage.mkdir(s);
    if (storage.isDirectory(s)) return;
    Log.p("Cannot create directory: " + s);
}

which is supposed to work like new File(file).getParentFile().mkdirs(). It might be wrong, but then it shouldn't run in the simulator either, so I'd call it a bug.

I get the message

Cannot create directory:
file:///data/user/0/my.package.name/files//dump/000/abcd

but the parent directory ("000") has been successfully created. Using adb shell, I can create the directory using

mkdir /data/data/my.package.name/files/dump/000/abcd

so I can't see what's wrong. Any idea?


Solution

  • There was (possibly still existent) problem with double slashes. My path was

    /dump/000/abcd
    

    and I transformed it via

    path -> APP_HOME_PATH + "/" + path
    

    into

    file:///data/user/0/my.package.name/files//dump/000/abcd
    

    which failed because of the double slashes, while

    dump/000/abcd
    

    transforms into

    file:///data/user/0/my.package.name/files/dump/000/abcd
    

    and works correctly.