Monday 22 December 2014

Android Example of Reading File From raw Folder

Hello friends'

Here is an example of reading file from raw folder in Android.

Make a file named my_file.txt (example) in raw folder of res and write some content on it.



In the Layout file one button and one textview is used.

when click on button, file will be read and its content will display on textview.

The layout file code:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/LinearLayout1"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:gravity="center"
    android:orientation="vertical" >

    <Button
        android:id="@+id/button"
        style="?android:attr/buttonStyleSmall"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Click here to read file" />

    <TextView
        android:id="@+id/textView"
        android:layout_width="match_parent"
        android:layout_height="200dp"
        android:text="Small Text"
        android:gravity="center"
        android:layout_marginTop="10dp"
        android:textAppearance="?android:attr/textAppearanceSmall" />

</LinearLayout>


MainActivity java file code:

package in.blogspot.longjamcode;

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.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;

public class MainActivity extends Activity {

private Button button;
private TextView textView;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
button = (Button) findViewById(R.id.button);
textView = (TextView) findViewById(R.id.textView);
button.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
try {
String string="";
StringBuffer stringBuffer = new StringBuffer();
InputStream inputStream = MainActivity.this.getResources().openRawResource(R.raw.my_file);
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
if (inputStream!=null) {
while ((string = reader.readLine()) != null) {
stringBuffer.append(string + "\n" );
}
}
inputStream.close();
textView.setText(stringBuffer);
}
catch (IOException e) {
e.printStackTrace();
}
}
});
}
}

The sample output:





















For full source code click here

No comments:

Post a Comment