Android – Read text file from assets folder

We can use assets folder in Android to store files that we want to use in the application as it is. Files in the assets folder are deployed to the device with the same name. For example, assets folder can be used to store application database. Files in this folder can be accessed using AssetManager class.

To read text from a file in the Assets folder, first create a text file with some text in the assets folder or just copy past file into the assets folder.

Java -Asset   Write following code to read contents of a text file from the assets folder

public void btnReadText_Click(View vw) {
 String fileContents = ReadFile("ReadMe.txt");
 Toast.makeText(getApplicationContext(), fileContents,
  Toast.LENGTH_SHORT).show();
}

public String ReadFile(String fileName) {
 BufferedReader br = null;
 String fileText = "";
 try {
  String str = "";
  StringBuffer buffer = new StringBuffer();
  AssetManager assetManager = getAssets();
  InputStream stream = assetManager.open(fileName);

  BufferedReader reader = new BufferedReader(new InputStreamReader(
   stream));
  if (stream != null) {
   while ((str = reader.readLine()) != null) {
    buffer.append(str);
   }
  }
  fileText = buffer.toString();
 } catch (IOException e) {
  e.printStackTrace();
 } finally {
  try {
   if (br != null)
    br.close();
  } catch (IOException ex) {
   ex.printStackTrace();
  }
 }
 return fileText;
}

Leave a Reply

Your email address will not be published. Required fields are marked *