关于文件删除,犯了很二的错误

根据指定Uri删除音频文件。

写了个方法:

	private void DelFileByUri(Uri uri){
		String[] proj = { MediaStore.Audio.Media.DATA };
		Cursor actualAudioCursor = managedQuery(uri,proj,null,null,null);
		int actual_audio_column_index = actualAudioCursor.getColumnIndexOrThrow(MediaStore.Audio.Media.DATA);
		actualAudioCursor.moveToFirst();
		String audio_path = actualAudioCursor.getString(actual_audio_column_index);
		Log.e("harlan", "audio_path:"+audio_path);
		File file = new File(audio_path);
		file.delete();
		Log.e("harlan", "DelFileByUri  File.exists():"+file.exists());
		Log.e("harlan", "DelFileByUri  File.delete():"+file.delete());
	}

最后2行log一直显示false。

我还犯二,以为文件路径问题。

恍然大悟才知道,此时file已被删除,调用exists和再次删除,当然出错。

正确的如下:

	private void DelFileByUri(Uri uri){
		String[] proj = { MediaStore.Audio.Media.DATA };
		Cursor actualAudioCursor = managedQuery(uri,proj,null,null,null);
		int actual_audio_column_index = actualAudioCursor.getColumnIndexOrThrow(MediaStore.Audio.Media.DATA);
		actualAudioCursor.moveToFirst();
		String audio_path = actualAudioCursor.getString(actual_audio_column_index);
		Log.e("harlan", "audio_path:"+audio_path);
		File file = new File(audio_path);
		Log.e("harlan", "DelFileByUri  File.exists():"+file.exists());
		boolean ifDeled = file.delete();
		Log.e("harlan", "DelFileByUri  File ifDeled:"+ifDeled);
	}



你可能感兴趣的:(java,android)