get String from Asset file via ByteArrayOutputStream - Android App

Android examples for App:Assets String

Description

get String from Asset file via ByteArrayOutputStream

Demo Code


//package com.java2s;
import android.content.Context;
import java.io.ByteArrayOutputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;

public class Main {

    public static String getString(Context context, String fileName) {
        String json = null;/*  w  w  w.j  ava 2s . c o  m*/
        try {
            InputStream in = context.getResources().getAssets()
                    .open(fileName);
            ByteArrayOutputStream out = new ByteArrayOutputStream();
            byte[] buffer = new byte[8192];
            int length;
            while ((length = in.read(buffer)) != -1)
                out.write(buffer, 0, length);
            in.close();
            out.close();
            byte[] data = out.toByteArray();
            json = new String(data);

        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return json;
    }
}

Related Tutorials