get Asset File Data into ByteArrayOutputStream - Android App

Android examples for App:Assets File

Description

get Asset File Data into ByteArrayOutputStream

Demo Code


//package com.java2s;
import java.io.ByteArrayOutputStream;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import android.content.Context;
import android.content.res.AssetManager;
import android.util.Log;

public class Main {
    private static final String TAG = "AssetHelper";

    static public void getFileData(Context ctx, String filename,
            ByteArrayOutputStream bos) throws IOException {
        AssetManager assetManager = ctx.getAssets();
        InputStream in = null;/*from www  .j  av a  2s. co m*/

        // Copy files from asset folder to application folder
        try {
            in = assetManager.open(filename);
            copyFile(in, bos);
        } catch (IOException e) {
            Log.e(TAG, e.getMessage());
            throw e;
        } finally {
            // Reclaim resources
            if (in != null) {
                in.close();
                in = null;
            }
            if (bos != null) {
                bos.flush();
                bos = null;
            }
        }
    }

    static private void copyFile(InputStream in, OutputStream out)
            throws IOException {
        byte[] buffer = new byte[1024];
        int read;

        // Copy from input stream to output stream
        while ((read = in.read(buffer)) != -1) {
            out.write(buffer, 0, read);
        }
    }
}

Related Tutorials