Getting Started in Android Development
Part 35 -
In this tutorial we will look at how to create and save a file within and Android app. The file will be a basic text file created from text entered into an EditText field.
The layout for this Activity, called activity_file_save.xml, is shown below:
In the java code, a file name is defined:
public final static String fileName = "textfiledata";
The code that is important to this task is contained within the onClick method associated with the save button.
The text entered in the EditText is retrieved using the code below:
String fileData = ourData.getText().toString();
There are then only three lines of code needed to save the file. Like all I/O actions, this code needs to be surrounded by a try and catch.
We need to create an object of the FileOutputStream class. We pass the file name and the mode. Here it is private so that it can be accessed by the app only and will be deleted if the app is deleted. There are also options for world readable and world writeable. These files are not deleted if the app is removed and really should only be used as a last resort.
FileOutputStream fileOut = openFileOutput(fileName, MODE_PRIVATE);
In this example we are using "internal" storage. This requires no Android permissions. Should you wish to use external storage, such as an SD card, then you will need to declare an Android permission in the Android Manifest file.
The next two lines of code write the byte stream to the file and close the file on completion.
After this tutorial your FileSaveActivity.java file will look similar to the one below:
Your MainActivity.java file will look similar to the one below:
Your Android Manifest file will look similar to the one below:
Download Download tutorial set 2