Gets binary content from uri as byte array - Android File Input Output

Android examples for File Input Output:Byte Array

Description

Gets binary content from uri as byte array

Demo Code

/*//from w w w . j a va2 s.c  om
 CanvasDrawUtils.java
 Copyright (c) 2015 NTT DOCOMO,INC.
 Released under the MIT license
 http://opensource.org/licenses/mit-license.php
 */
//package com.java2s;
import android.content.ContentResolver;
import android.content.Context;

import android.net.Uri;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;

public class Main {
    /**
     * Defined a size of buffer.
     */
    private static final int BUF_SIZE = 4096;

    /**
     * Gets binary from uri.
     *
     * @param context context
     * @param uri     uri
     * @return byte[] or null on error
     */
    public static byte[] getContentData(final Context context,
            final String uri) {
        if (uri == null) {
            return null;
        }
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        InputStream in = null;
        byte[] buf = new byte[BUF_SIZE];
        int len;
        try {
            ContentResolver r = context.getContentResolver();
            in = r.openInputStream(Uri.parse(uri));
            while ((len = in.read(buf)) > 0) {
                out.write(buf, 0, len);
            }
            return out.toByteArray();
        } catch (IOException e) {
            return null;
        } finally {
            if (in != null) {
                try {
                    in.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}

Related Tutorials