ContentProvider openOutputStream - 如何创建文件

时间:2014-05-26 11:29:53

标签: android android-contentprovider

我想用ContentProvider保存/加载二进制数据。为了保存,我写了这段代码:

        long id = database.insert(TABLE_NAME, null, values);

        Uri uri = ContentUris.withAppendedId(
                LocationContentProvider.CONTENT_URI, id);

        OutputStream outStream;
        try {
            Bitmap bmp = ...

            if (bmp != null) {
                outStream = cr.openOutputStream(uri);
                ImageUtils.saveToStream(bmp, outStream,
                        Bitmap.CompressFormat.PNG);
                outStream.close();
                bmp.recycle();
            }

        } catch (FileNotFoundException e) {
            e.printStackTrace();
            Log.d(TAG, "Could not save logo to " + uri.toString());
        } catch (IOException e) {
            e.printStackTrace();
            Log.d(TAG, "Could not save logo to " + uri.toString());
        }

但当然,最初该文件不存在。所以我得到了FileNotFoundException。我的问题是,如果尚未存在,我如何强制ContentProvider创建文件?我需要实现ContentProvider.openFile吗?

@Override
public ParcelFileDescriptor openFile(Uri uri, String mode)
        throws FileNotFoundException {
    // TODO Auto-generated method stub
    return super.openFile(uri, mode);
}

1 个答案:

答案 0 :(得分:0)

我终于想通了你必须重写ContentProvider.openFile。有关详细信息,请参阅this post。 ContentProvider中的我的方法如下所示:

public ParcelFileDescriptor openFile(Uri uri, String mode)
        throws FileNotFoundException {

    ContextWrapper cw = new ContextWrapper(getContext());

    // path to /data/data/yourapp/app_data/dir
    File directory = cw.getDir(BASE_PATH, Context.MODE_WORLD_WRITEABLE);
    directory.mkdirs();

    long id = ContentUris.parseId(uri);
    File path = new File(directory, String.valueOf(id));

    int imode = 0;
    if (mode.contains("w")) {
        imode |= ParcelFileDescriptor.MODE_WRITE_ONLY;
        if (!path.exists()) {
            try {
                path.createNewFile();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    }
    if (mode.contains("r"))
        imode |= ParcelFileDescriptor.MODE_READ_ONLY;
    if (mode.contains("+"))
        imode |= ParcelFileDescriptor.MODE_APPEND;

    return ParcelFileDescriptor.open(path, imode);
}
相关问题