North Border Software

Home Tutorials Hints & Tips About
Share on Facebook Share on Twitter

Getting Started in Android Development

Part 36 - Loading a File with FileInputStream

Loading a saved file is really just as straightforward as saving the file. For this example a simple layout called acivity_file_load.xml has been defined. This has just a TextView and the code is below:

We will work with the file saved in part 35. This was called "textfiledata" and so we define a constant string:

public final static String fileName = "textfiledata";

Inside of a try and catch we first load the file using the fileInputStream class.

FileInputStream fileIn = openFileInput(fileName);

We initialize an empty string variable that will hold the file data and we also initialize a counter.

String fileData = "";
int count;

A while loop is needed to get the data from the file a byte at a time and we concatenate the fileData string with the retrieved data.

while ((count = != -1)
   {fileData += Character.toString((char)count);}

The read() method returns -1 when the end of the byte stream is reached. The += ensures we take the previous value of fileData and concatenate the new value onto the existing value. The final task is to simply set the value of the TextView with the fileData string.

After this tutorial your file should look similar to the one below:

Your file should look similar to the one below:

Your Android Manifest file should look similar to the one below:

Download Download tutorial set 2

© 2015 North Border Software All rights reserved
Privacy and Cookies Terms of Use Disclaimer Copyright
North Border Software Logo

Android Apps and Training