Read a text file from assets - Android App

Android examples for App:Assets File

Description

Read a text file from assets

Demo Code

/**//ww  w.  j av  a 2s.c o  m
 * (c) Winterwell Associates Ltd, used under MIT License. This file is background IP.
 */
//package com.java2s;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;

import android.content.Context;

import android.content.res.AssetManager;

public class Main {
    /**
     * Read a text file from assets
     * 
     * @param context
     * @param fileName
     * @return
     */
    public static String read(Context context, String fileName) {
        try {
            AssetManager am = context.getAssets();
            InputStream in = am.open(fileName);
            // String pckg = context.getPackageName();
            // ContentResolver cr = context.getContentResolver();
            // Uri uri = Uri.parse("android.resource://"+pckg+"/"+fileName);
            // InputStream in = cr.openInputStream(uri);
            String txt = read(new InputStreamReader(in));
            return txt;
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * @param r Will be read and closed
     * @return The contents of input
     */
    public static String read(Reader r) {
        try {
            BufferedReader reader = r instanceof BufferedReader ? (BufferedReader) r
                    : new BufferedReader(r);
            final int bufSize = 8192; // this is the default BufferredReader
            // buffer size
            StringBuilder sb = new StringBuilder(bufSize);
            char[] cbuf = new char[bufSize];
            while (true) {
                int chars = reader.read(cbuf);
                if (chars == -1)
                    break;
                sb.append(cbuf, 0, chars);
            }
            return sb.toString();
        } catch (IOException e) {
            throw new RuntimeException(e);
        } finally {
            try {
                r.close();
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
        }
    }

    public static String read(InputStream inputStream) {
        return read(new InputStreamReader(inputStream));
    }
}

Related Tutorials