Posted By Our Mentors
Amreen Khan
Android Developer
animesh bansal
iphone App Developer
Devendra chouksey
Android Developer
Dilip Saket
IOS apps developer
Hemraj Jhariya
iOS Developer
Jaihind singh Rajput
Smart Phone App Dev
Mujahid khan
Android developer
Narendra Yadav
android developer
Narinder Gupta
Mobile App Architect
Pradeep singh Thakur
Mobile App Architect
Sanjay Sharma
Andriod Developer
Shakti Rajpal
IT Architect
Soniya Vishwakarma
iPhone App Developer
Sunil Raghuwanshi
iPhone App Developer
Supriya Kapse
Senior developer
View current Topics
How to read a file from the assets directory in android? Android
In this post I will show you how to read a text file in ANDOID. Let your file is in the assets folder of your ANDOID project. If you want to read the particular file content used in your project then do the following..
Posted By: Amreen Khan Date: 09 Jul 2012 View: 945
      Rate This !!



In main.xml I have added an textview to show the content of the file.

main.xml:-
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >

    <TextView
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:id="@+id/txtfile" />

</LinearLayout>
 

java code:-
copy and paste the below code in your project activity's oncreate() method.

 TextView txtFile = (TextView) findViewById(R.id.txtfile);
        InputStream is;
       
        //Most clients will use input streams that read data from the file system (FileInputStream),
        //the network (getInputStream()/getInputStream()), or from an in-memory byte array (ByteArrayInputStream).

 
        try
        {
            //open the file from the asset folder.
            is = getAssets().open("android.txt");
            int siz = is.available();
            byte[] buffer = new byte[siz];
            is.read(buffer);
            //This text contains the content of the file..
            String text = new String(buffer);
            txtFile.setText(text);
            //close the file.
            is.close();
        }
        catch (Exception e)
        {
             Toast.makeText(ReadTxtActivity.this,"File Not Found Error.Please ensure that file is not deleted.", Toast.LENGTH_SHORT).show();
        }

Note:-
The file is named “android.txt”  exists in assets folder.
This example reads the file line by line using read() function till the end of the file.




Posted Queries