Java tutorial
//package com.java2s; //License from project: Apache License import java.io.File; import java.io.FileOutputStream; import java.io.InputStream; import java.io.OutputStream; import android.content.Context; import android.database.Cursor; import android.net.Uri; import android.provider.MediaStore; import android.util.Log; public class Main { public static File getFile(Context context, Uri uri, boolean forceCreation) { if (!forceCreation && "file".equalsIgnoreCase(uri.getScheme())) { return new File(uri.getPath()); } File file = null; try { File root = context.getFilesDir(); if (root == null) { throw new Exception("data dir not found"); } file = new File(root, getFilename(context, uri)); file.delete(); InputStream is = context.getContentResolver().openInputStream(uri); OutputStream os = new FileOutputStream(file); byte[] buf = new byte[1024]; int cnt = is.read(buf); while (cnt > 0) { os.write(buf, 0, cnt); cnt = is.read(buf); } os.close(); is.close(); file.deleteOnExit(); } catch (Exception e) { Log.e("OpenFile", e.getMessage(), e); } return file; } public static String getPath(Context context, Uri uri) { if ("content".equalsIgnoreCase(uri.getScheme())) { String[] projection = { "_data" }; Cursor cursor; try { cursor = context.getContentResolver().query(uri, projection, null, null, null); int column_index = cursor.getColumnIndex("_data"); if (column_index != -1 && cursor.moveToFirst()) { String path = cursor.getString(column_index); if (path == null) { path = getNewTemporaryFilePath(context, uri); } return path; } else { return getNewTemporaryFilePath(context, uri); } } catch (Exception e) { return getNewTemporaryFilePath(context, uri); } } else if ("file".equalsIgnoreCase(uri.getScheme())) { return uri.getPath(); } return null; } /** * Return the filename from a uri. */ public static String getFilename(Context c, Uri uri) { try { String scheme = uri.getScheme(); if (scheme.equals("file")) { return uri.getLastPathSegment(); } else if (scheme.equals("content")) { String[] proj = { MediaStore.Files.FileColumns.DISPLAY_NAME }; Cursor cursor = c.getContentResolver().query(uri, proj, null, null, null); if (cursor != null && cursor.getCount() != 0) { int columnIndex = cursor.getColumnIndexOrThrow(MediaStore.Files.FileColumns.DISPLAY_NAME); cursor.moveToFirst(); return cursor.getString(columnIndex); } } } catch (Exception e) { e.printStackTrace(); } return null; } public static String getNewTemporaryFilePath(Context context, Uri uri) { File file = getFile(context, uri, true); return file == null ? null : file.getPath(); } }