Get text file content from raw folder to StringBuilder Android example

StringBuilder, res/raw folder, try catch finaly throws, BufferedReader, InputStream, openRawResource, getResources Android example

MainActivity.java

 
public class MainActivity extends Activity {
TextView txtV;
	Context cntx;
 
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        txtV = (TextView)findViewById(R.id.idLabel);
        cntx = this;
        try {
			StringBuilder strBuilder = myFunction(cntx);
			txtV.setText(strBuilder);
		} catch (IOException e) {
			e.printStackTrace();
		}
 
 
    }
 
 
    private StringBuilder myFunction(Context context) throws IOException {
        final Resources resources =  context.getResources();
        InputStream inputStream = resources.openRawResource(R.raw.my_file);
        BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
        StringBuilder strBuild = new StringBuilder();
        try {
            String line;
            while ((line = reader.readLine()) != null) {
            	strBuild.append(line);
            }
        } finally {
            reader.close();
        }
       return strBuild; 
 
    }
}
This entry was posted in Android Examples Code and tagged , , , , , , . Bookmark the permalink.


Comments are closed.

8,614 views