read File from asset via AssetManager - Android App

Android examples for App:Assets File

Description

read File from asset via AssetManager

Demo Code


//package com.java2s;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import android.app.Activity;
import android.content.res.AssetManager;

public class Main {
    public static String readFile(Activity activity, String fileName) {
        AssetManager assets = activity.getAssets();
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        byte buf[] = new byte[1024];
        int len;/*from  ww w.  j  av  a  2  s. c o m*/
        try {
            InputStream inputStream = assets.open(fileName);
            while ((len = inputStream.read(buf)) != -1) {
                outputStream.write(buf, 0, len);
            }
            outputStream.close();
            inputStream.close();
            return outputStream.toString();
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
    }
}

Related Tutorials