Thursday, 1 July 2010

Display text file in /res/raw

Android can handle text file as raw.

Display text file in /res/raw

Create a text file, named hello.txt, and save it in the folder /res/raw. The files inside /res/raw will be traded as raw files, they will not be compiled. They will be moved to application package as they are.

main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="@string/hello"
/>
<TextView
android:id="@+id/hellotxt"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:textSize="22px"
/>
</LinearLayout>


AndroidTxt.java
package com.exercise.AndroidTxt;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;

import android.app.Activity;
import android.os.Bundle;
import android.widget.TextView;

public class AndroidTxt extends Activity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);

TextView helloTxt = (TextView)findViewById(R.id.hellotxt);
helloTxt.setText(readTxt());
}

private String readTxt(){

InputStream inputStream = getResources().openRawResource(R.raw.hello);

ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();

int i;
try {
i = inputStream.read();
while (i != -1)
{
byteArrayOutputStream.write(i);
i = inputStream.read();
}
inputStream.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

return byteArrayOutputStream.toString();
}
}


Download the files.

No comments:

Post a Comment