load Text From Assets - Android android.content

Android examples for android.content:Asset

Description

load Text From Assets

Demo Code

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;

import android.content.Context;

public class Main {

  /**//ww  w.  j a v  a 2 s  .c o  m
   * Loads lines of text from the given path in the assets directory.
   * 
   * @param context
   *          Application context.
   * @param path
   *          Path in the assets folder to the text file to load.
   * @return String array representing lines of text in the file.
   */
  public static String[] loadTextFromAssets(Context context, String path) {
    try {
      // Open the input stream to the text in assets
      InputStream inputStream = context.getAssets().open(path);
      InputStreamReader inputStreamReader = new InputStreamReader(inputStream);
      BufferedReader bufferedReader = new BufferedReader(inputStreamReader);

      List<String> lines = new ArrayList<String>();

      String line;
      while ((line = bufferedReader.readLine()) != null) {
        lines.add(line);
      }

      inputStream.close();

      return lines.toArray(new String[lines.size()]);
    } catch (IOException e) {
      return null;
    }

  }

}

Related Tutorials