read Assets Text to String list - Android App

Android examples for App:Assets String

Description

read Assets Text to String list

Demo Code


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

public class Main {
  static List<String> readAssetsText(String assetName) throws IOException {
    InputStream is = null;//from  w  w  w  .  jav a2  s.  c  o  m
    InputStreamReader isr = null;
    BufferedReader br = null;
    List<String> lines = new ArrayList<String>();
    try {
      is = openFile(assetName);
      isr = new InputStreamReader(is, "UTF-8");
      br = new BufferedReader(isr);
      String line = null;
      while ((line = br.readLine()) != null) {
        lines.add(line);
      }
    } finally {
      closeQuietly(br);
      closeQuietly(isr);
      closeQuietly(is);
    }
    return lines;
  }

  private static InputStream openFile(String filename) throws IOException {
    return Main.class.getClassLoader().getResourceAsStream(filename);
  }

  private static void closeQuietly(InputStream is) {
    if (is != null) {
      try {
        is.close();
      } catch (IOException e) {
        e.printStackTrace();
      }
    }
  }

  private static void closeQuietly(Reader reader) {
    if (reader != null) {
      try {
        reader.close();
      } catch (IOException e) {
        e.printStackTrace();
      }
    }
  }
}

Related Tutorials