Basics of File Handling Write operations using IO Class in Android Operating System (Part 2)

Опубликовано: 11 Октябрь 2024
на канале: Sarthak Education (C D Patel Digital Room)
185
7

Android provides many kinds of storage for applications to store their data. These storage places are shared preferences, internal and external storage, SQLite storage, and storage via network connection.

In this video we are going to look at the internal storage. Internal storage is the storage of the private data on the device memory.

By default these files are private and are accessed by only your application and get deleted , when user delete your application.

Writing file
In order to use internal storage to write some data in the file, call the openFileOutput() method with the name of the file and the mode. The mode could be private , public e.t.c. Its syntax is given below −

FileOutputStream fOut = openFileOutput("file name here",MODE_WORLD_READABLE);
The method openFileOutput() returns an instance of FileOutputStream. So you receive it in the object of FileInputStream. After that you can call write method to write data on the file. Its syntax is given below −

String str = "data";
fOut.write(str.getBytes());
fOut.close();

Reading file
In order to read from the file you just created , call the openFileInput() method with the name of the file. It returns an instance of FileInputStream. Its syntax is given below −

FileInputStream fin = openFileInput(file);
After that, you can call read method to read one character at a time from the file and then you can print it. Its syntax is given below −

int c;
String temp="";
while( (c = fin.read()) != -1){
temp = temp + Character.toString((char)c);
}

//string temp contains all the data of the file.
fin.close();
Apart from the the methods of write and close, there are other methods provided by the FileOutputStream class for better writing files.