File.canWrite() - Can't use?


#1

Here is the code:

[code]
public boolean saveExtCrimes() {
boolean result = true;

	String state = Environment.getExternalStorageState();
	if (!(Environment.MEDIA_MOUNTED.equals(state))) {
		return false;
	}

	File path = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_MUSIC);
	File file = new File(path, FILENAME);
	path.mkdirs();

*** NOTE: the check returns false, even though the write operation is later successful!

	if (file.canWrite() == false) {
		Log.d(TAG, "saveExtCrimes() cannot write to file: " + file.getAbsolutePath());
		//return false;
	}
	
	CiJSONSerializer serializer = new CiJSONSerializer();
	try {
		serializer.saveCrimesExternal(mCrimes, file);
		Log.d(TAG, "crimes saved to external file");
	} catch (Exception e) {
		Log.e(TAG, "Error saving crimes externally: ", e);
		return false;
	}

	return result;
}[/code]

I added the [color=#BF0000]File.canWrite()[/color] check because I got a permission exception that was later solved by the other post that shows what we need to add to the manifest.

However, even with the manifest change, the[color=#BF0000] canWrite()[/color] check returns false. I commented out the return statement, and the code then succeeds to save the Crime data to the external storage, but I still get the LogCat message.

[color=#4000FF]06-29 23:50:47.135: D/CrimeLab(1489): saveExtCrimes() cannot write to file: /mnt/sdcard/Music/crimes.json
06-29 23:50:47.235: D/CrimeLab(1489): crimes saved to external file
[/color]

Thanks!


#2

I’m not seeing a call to canWrite. Your call to getExternalStorageState should be sufficient, though - it’s very similar we do in our own code. canWrite() just does a permission check on the file (in this case, a directory).


#3

It ended up working the next day. So, it seems to be unreliable in the Android environment.

I guess the best solution is to do the MEDIA_MOUNTED check and use try/catch for everything else that could go wrong after that.

Thanks.