Home Tutorials Hints & Tips

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 = fileIn.read()) != -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 FileLoadActivity.java file should look similar to the one below:

Your MainActivity.java file should look similar to the one below:

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

Download Download tutorial set 2

Privacy and Cookies Disclaimer Copyright
© 2015 - 2018 North Border Tech Training All rights reserved