File mkdirs() method not working in android/java
- by Leif Andersen
I've been pulling out my hair on this for a while now. The following method is supposed to download a file, and save it to the location specified on the hard drive.
private static void saveImage(Context context, boolean backgroundUpdate, URL url, File file) {
if (!Tools.checkNetworkState(context, backgroundUpdate))
return;
// Get the image
try {
// Make the file
file.getParentFile().mkdirs();
// Set up the connection
URLConnection uCon = url.openConnection();
InputStream is = uCon.getInputStream();
BufferedInputStream bis = new BufferedInputStream(is);
// Download the data
ByteArrayBuffer baf = new ByteArrayBuffer(50);
int current = 0;
while ((current = bis.read()) != -1) {
baf.append((byte) current);
}
// Write the bits to the file
OutputStream os = new FileOutputStream(file);
os.write(baf.toByteArray());
os.close();
} catch (Exception e) {
// Any exception is probably a newtork faiilure, bail
return;
}
}
Also, if the file doesn't exist, it is supposed to make the directory for the file. (And if there is another file already in that spot, it should just not do anything). However, for some reason, the mkdirs() method never makes the directory. I've tried everything from explicit parentheses, to explicitly making the parent file class, and nothing seems to work. I'm fairly certain that the drive is writable, as it's only called after that has already been determined, also that is true after running through it while debugging. So the method fails because the parent directories aren't made. Can anyone tell me if there is anything wrong with the way I'm calling it?
Also, if it helps, here is the source for the file I'm calling it in:
https://github.com/LeifAndersen/NetCatch/blob/master/src/net/leifandersen/mobile/android/netcatch/services/RSSService.java
Thank you