This article is about how to (write a file to / read a file from) the internal storage of an android device with the help of a simple application.
Android Internal Storage
- Android Internal Storage is the device memory in which we store the files.
- The file stored in the internal storage is private in default, and only the same application accesses it. They cannot be accessed from outside the application.
- When the user uninstalls the application from the device, its internal storage file will also be removed.
- All android app internal data files are saved in the /data/data/<your app package name> folder.
- The package name folder (i.e /data/data/<your app package name>) by default contains files and cache subfolders.
- files: used to save general files and getFilesDir() method returns this folder.
- cache: used to save cached files and getCacheDir() method returns this folder.
Write to File in Internal Storage
To write a file to the internal storage of the device, the java.io package offers openFileOutput() method which returns the instance of FileOutputStream class. To write the data to a file call the BufferedWriter().write().
Write File to files Folder
You can use any of the two methods to create a file in the files folder.
Method 1:
Use getFilesDir() to get files folder.
File file = new File(getFilesDir(), fileName); FileOutputStream fileOutputStream = new FileOutputStream(file); OutputStreamWriter outputStreamWriter = new OutputStreamWriter(fileOutputStream); BufferedWriter bufferedWriter = new BufferedWriter(outputStreamWriter); bufferedWriter.write(data);
Method 2:
Call Context’s openFileOutput() method to get FileOutputStream object.
This method takes two parameters, The first parameter is the file name and the second parameter’s value can be:
- Context.MODE_PRIVATE : This means this file can only be read/write by this android app that creates it. This mode will overwrite an existing file, if not exist then create it.
- Context.MODE_APPEND : This mode will append data to the existing file. If not exist it will create a new one.
FileOutputStream fileOutputStream = getApplicationContext().openFileOutput(fileName, Context.MODE_PRIVATE);
OutputStreamWriter outputStreamWriter = new OutputStreamWriter(fileOutputStream);
BufferedWriter bufferedWriter = new BufferedWriter(outputStreamWriter);
bufferedWriter.write(data);
Write File to cache Folder
Use getCacheDir() to get cache folder.
File file = new File(getCacheDir(), fileName); FileOutputStream fileOutputStream = new FileOutputStream(file);
Reading Files from Internal Storage
To read a file from the internal storage of the device, the java.io package offers openFileInput() method which returns the instance of FileInputStream class. To read the data from file call the BufferedReader().readLine().
Read File from files Folder
FileInputStream fileInputStream = getApplicationContext().openFileInput(fileName); InputStreamReader inputStreamReader = new InputStreamReader(fileInputStream); BufferedReader bufferedReader = new BufferedReader(inputStreamReader); String lineData = bufferedReader.readLine();
Read File from cache Folder
File file = new File(getCacheDir(),fileName); FileInputStream fileInputStream = new FileInputStream(file);
Creating new project
Create a new project by going to File ⇒ New Android Project, select Empty Activity, provide app name, select language to java and then finally click on finish.
Creating the XML file
The below layout file consist of one EditText and four buttons with label text WRITE TO FILE, READ FROM FILE, CREATE CACHED FILE and READ CACHED FILE.
activity_main.xml
<?xml version="1.0" encoding="utf-8"?> <androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:layout_marginLeft="10dp" android:layout_marginRight="10dp" tools:context=".MainActivity"> <EditText android:id="@+id/edt_input" android:layout_width="match_parent" android:layout_height="wrap_content" android:hint="Enter Input" android:layout_marginTop="20dp" app:layout_constraintEnd_toEndOf="parent" app:layout_constraintHorizontal_bias="0.5" app:layout_constraintStart_toStartOf="parent" app:layout_constraintTop_toTopOf="parent" /> <Button android:id="@+id/btn_write_to_file" android:layout_width="match_parent" android:layout_height="wrap_content" android:text="WRITE TO FILE" android:layout_marginTop="20dp" app:layout_constraintEnd_toEndOf="parent" app:layout_constraintHorizontal_bias="0.0" app:layout_constraintStart_toStartOf="parent" app:layout_constraintTop_toBottomOf="@+id/edt_input" /> <Button android:id="@+id/btn_read_from_file" android:layout_width="match_parent" android:layout_height="wrap_content" android:text="READ FROM FILE" app:layout_constraintEnd_toEndOf="parent" app:layout_constraintStart_toStartOf="parent" app:layout_constraintTop_toBottomOf="@+id/btn_write_to_file" /> <Button android:id="@+id/btn_create_cached_file" android:layout_width="match_parent" android:layout_height="wrap_content" android:text="CREATE CACHED FILE" app:layout_constraintEnd_toEndOf="parent" app:layout_constraintStart_toStartOf="parent" app:layout_constraintTop_toBottomOf="@+id/btn_read_from_file" /> <Button android:id="@+id/btn_read_cached_file" android:layout_width="match_parent" android:layout_height="wrap_content" android:text="READ CACHED FILE" app:layout_constraintEnd_toEndOf="parent" app:layout_constraintStart_toStartOf="parent" app:layout_constraintTop_toBottomOf="@+id/btn_create_cached_file" /> </androidx.constraintlayout.widget.ConstraintLayout>
Implementing code in Activity
Here on click of each button perform different operation:
- WRITE TO FILE: writes to a file “User” created inside the files folder.
- READ FROM FILE: reads from the “User” file.
- CREATE CACHED FILE: writes to a cache file “UserCache” created inside the cache folder.
- READ CACHED FILE: reads from “UserCache” file.
MainActivity.java
package com.c1ctech.readwritefileexp; import android.content.Context; import android.graphics.Color; import android.os.Bundle; import android.text.TextUtils; import android.util.Log; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.Toast; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import androidx.appcompat.app.AppCompatActivity; public class MainActivity extends AppCompatActivity { private String TAG_WRITE_READ_FILE = "TAG_WRITE_READ_FILE"; EditText edtInput; Button btnWriteToFile, btnReadFromFile, btnCreateCachedFile, btnReadCachedFile; String userData; String fileName; String cacheFileName; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); getViewsById(); fileName = "User"; cacheFileName = "UserCache";
//write to internal file btnWriteToFile.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { userData = edtInput.getText().toString(); if (TextUtils.isEmpty(userData)) { Toast.makeText(getApplicationContext(), "Input data can not be empty.", Toast.LENGTH_LONG).show(); return; } else { try { FileOutputStream fileOutputStream = getApplicationContext().openFileOutput(fileName, Context.MODE_PRIVATE); writeDataToFile(fileOutputStream, userData); Toast.makeText(getApplicationContext(), "Data has been written to file " + fileName + " " + getFilesDir().getAbsolutePath(), Toast.LENGTH_LONG).show(); } catch (FileNotFoundException ex) { Log.e(TAG_WRITE_READ_FILE, ex.getMessage(), ex); } } } }); //read from internal file btnReadFromFile.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { try { FileInputStream fileInputStream = getApplicationContext().openFileInput(fileName); String fileData = readDataFromFile(fileInputStream); if (fileData.length() > 0) { edtInput.setText(fileData); edtInput.setTextColor(Color.BLUE); Toast.makeText(getApplicationContext(), "Load saved data from file " + fileName + " " + getFilesDir().getAbsolutePath(), Toast.LENGTH_SHORT).show(); Log.e(TAG_WRITE_READ_FILE, getFilesDir().getAbsolutePath()); } else { Toast.makeText(getApplicationContext(), "Not load any data.", Toast.LENGTH_SHORT).show(); } } catch (FileNotFoundException ex) { Log.e(TAG_WRITE_READ_FILE, ex.getMessage(), ex); } } }); //write to internal cache file btnCreateCachedFile.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { String userData = edtInput.getText().toString(); if (TextUtils.isEmpty(userData)) { Toast.makeText(getApplicationContext(), "Input data can not be empty.", Toast.LENGTH_LONG).show(); return; } else { File file = new File(getCacheDir(), cacheFileName); writeDataToFile(file, userData); Toast.makeText(getApplicationContext(), "Cached file " + cacheFileName + " is created " + " " + getCacheDir().getAbsolutePath(), Toast.LENGTH_LONG).show(); } } }); //read from cache file btnReadCachedFile.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { try { Context ctx = getApplicationContext(); File cacheFileDir = new File(getCacheDir(), cacheFileName); FileInputStream fileInputStream = new FileInputStream(cacheFileDir); String fileData = readDataFromFile(fileInputStream); if (fileData.length() > 0) { edtInput.setText(fileData); edtInput.setTextColor(Color.MAGENTA); Toast.makeText(ctx, "Load saved cache data from file " + cacheFileName + " " + getCacheDir().getAbsolutePath(), Toast.LENGTH_SHORT).show(); } else { Toast.makeText(ctx, "Not load any cache data.", Toast.LENGTH_SHORT).show(); } } catch (FileNotFoundException ex) { Log.e(TAG_WRITE_READ_FILE, ex.getMessage(), ex); } } }); }
//getting views by its id private void getViewsById() { edtInput = findViewById(R.id.edt_input); btnWriteToFile = findViewById(R.id.btn_write_to_file); btnReadFromFile = findViewById(R.id.btn_read_from_file); btnCreateCachedFile = findViewById(R.id.btn_create_cached_file); btnReadCachedFile = findViewById(R.id.btn_read_cached_file); } // This method will write data to file. private void writeDataToFile(File file, String data) { try { FileOutputStream fileOutputStream = new FileOutputStream(file); this.writeDataToFile(fileOutputStream, data); fileOutputStream.close(); } catch (FileNotFoundException ex) { Log.e(TAG_WRITE_READ_FILE, ex.getMessage(), ex); } catch (IOException ex) { Log.e(TAG_WRITE_READ_FILE, ex.getMessage(), ex); } } // This method will write data to FileOutputStream. private void writeDataToFile(FileOutputStream fileOutputStream, String data) { try { OutputStreamWriter outputStreamWriter = new OutputStreamWriter(fileOutputStream); BufferedWriter bufferedWriter = new BufferedWriter(outputStreamWriter); bufferedWriter.write(data); bufferedWriter.flush(); bufferedWriter.close(); outputStreamWriter.close(); } catch (IOException ex) { Log.e(TAG_WRITE_READ_FILE, ex.getMessage(), ex); } } //This method will read data from FileInputStream private String readDataFromFile(FileInputStream fileInputStream) { StringBuffer retBuf = new StringBuffer(); try { if (fileInputStream != null) { InputStreamReader inputStreamReader = new InputStreamReader(fileInputStream); BufferedReader bufferedReader = new BufferedReader(inputStreamReader); String lineData = bufferedReader.readLine(); while (lineData != null) { retBuf.append(lineData); lineData = bufferedReader.readLine(); } } } catch (IOException ex) { Log.e(TAG_WRITE_READ_FILE, ex.getMessage(), ex); } catch (Exception ex) { Log.e(TAG_WRITE_READ_FILE, ex.getMessage(), ex); } finally { return retBuf.toString(); } } }
When you run the app it will look like this:
Write to/read from a file in the files folder:
Write to/read from a file in the cache folder: