Read Text file in android Example


Introduction
            Reading a text file is a common functionality in all software's and its the same in case of Android applications also. In this example we will read the text file from res/drawable folder line by line and store it into a string.
Now, lets go ahead and see how to get this done.

Step 1: Copy/Create your text file in res/drawable folder
            For this tutorial I have copy pasted a text file named filetoread.txt into res/drawable folder as shown below. Note, ensure your file name is smallcase else, you will get error.

Directory Structure


Step 2 : Read the text file
             Since we have placed our text file in res/drawable folder, we should use openRawResource() class to read the file, since its a application resource.
InputStream is = this.getResources().openRawResource(R.drawable.filetoread);

Then use BufferedReader class to read the input stream as shown below,
BufferedReader reader = new BufferedReader(new InputStreamReader(is));

Then read the BufferedReader object line by line
while ((data = reader.readLine()) != null)
{
   sbuffer.append(data + "\n");
}

Thats it, we are almost done with reading text file in Android.

Step 3 : Display text file content in Toast
             Just display the string buffer in Toast as shown below,
Toast.makeText(getBaseContext(), sbuffer.toString(), Toast.LENGTH_LONG).show();

To summarize, first place the text file in res/drawable folder, then read the file line by line and append the string data to string buffer and display this in a toast that it.
Now run the program, you can see the content of the file in Toast message.


MainActivity.java

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import android.app.Activity;
import android.os.Bundle;
import android.view.Menu;
import android.widget.Toast;

public class MainActivity extends Activity {

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
String data = "";
StringBuffer sbuffer = new StringBuffer();
InputStream is = this.getResources().openRawResource(
R.drawable.filetoread);
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
if (is != null) {
try {
while ((data = reader.readLine()) != null) {
sbuffer.append(data + "\n");
}
is.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
Toast.makeText(getBaseContext(), sbuffer.toString(), Toast.LENGTH_LONG)
.show();
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}

}

Source Code of this application




Reactions:

0 comments :

Post a Comment