<p>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.</p> 
 
 
 
<div class="wp-block-buttons is-content-justification-center is-layout-flex wp-block-buttons-is-layout-flex"> 
<div class="wp-block-button"><a class="wp-block-button__link has-white-color has-text-color has-background" style="background-color: #520599;" href="https://github.com/arunk7839/AndroidReadWriteFileExample"><strong>DOWNLOAD CODE</strong></a></div> 
</div> 
<p><amp-youtube layout="responsive" width="1200" height="675" data-videoid="QlSyX8FfbtQ" title="Android Read and Write Internal Storage Example"><a placeholder href="https://youtu.be/QlSyX8FfbtQ"><img src="https://i.ytimg.com/vi/QlSyX8FfbtQ/hqdefault.jpg" layout="fill" object-fit="cover" alt="Android Read and Write Internal Storage Example"></a></amp-youtube></p> 
<h4><span style="color: #000080;"><b>Android Internal Storage</b></span></h4> 
 
 
 
<ul class="wp-block-list"> 
<li class="p1"><span style="color: #0000ff;"><b>Android Internal Storage</b></span> is the device memory in which we store the files.</li> 
<li class="p1">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.</li> 
<li class="p1">When the user uninstalls the application from the device, its internal storage file will also be removed.</li> 
<li>All android app internal data files are saved in the <span style="color: #008000;"><strong>/data/data/<;your app package name>;</strong></span> folder.</li> 
<li>The package name folder (i.e <span style="color: #008000;"><strong>/data/data/<;your app package name>;</strong></span>) by default contains <span style="color: #0000ff;"><strong>files</strong></span> and <span style="color: #0000ff;"><strong>cache</strong></span> subfolders. 
<ul> 
<li class="li1"><span style="color: #0000ff;"><b>files</b>:</span><b> </b>used to save general files and <a href="https://developer.android.com/reference/android/content/Context.html#getFilesDir()"><span class="s1"><b><span style="color: #008000;">getFilesDir()</span></b></span></a> method returns this folder.</li> 
<li class="li1"><span style="color: #0000ff;"><b>cache</b>:</span> used to save cached files and <span style="color: #008000;"><a style="color: #008000;" href="https://developer.android.com/reference/android/content/Context.html#getCacheDir()"><span class="s1"><b>getCacheDir()</b></span></a> </span>method returns this folder.</li> 
</ul> 
</li> 
</ul> 
 
 
 
<h4 class="h2 wp-block-heading"><strong><span style="color: #000080;">Write to File in Internal Storage</span></strong></h4> 
<p>To write a file to the internal storage of the device, the <span style="color: #0000ff;"><b>java.io</b></span> package offers <span style="color: #008000;"><b>openFileOutput()</b></span> method which returns the instance of <span style="color: #008000;"><b>FileOutputStream</b></span> class. To write the data to a file call the <b><span style="color: #008000;">BufferedWriter().write()</span>.</b></p> 
 
 
 
<h4 class="wp-block-heading"><strong><span style="color: #0000ff;">Write File to files Folder</span></strong></h4> 
<p>You can use any of the two methods to create a file in the files folder.</p> 
 
 
 
<p><strong><span style="color: #0000ff;">Method 1:</span></strong></p> 
 
 
 
<p>Use <span style="color: #008000;"><strong>getFilesDir()</strong></span> to get files folder.</p> 
 
 
 
<pre class="wp-block-preformatted"> File file = new File(getFilesDir(), fileName); 
 FileOutputStream fileOutputStream = new FileOutputStream(file); 
 OutputStreamWriter outputStreamWriter = new OutputStreamWriter(fileOutputStream); 
 BufferedWriter bufferedWriter = new BufferedWriter(outputStreamWriter); 
 bufferedWriter.write(data);</pre> 
 
 
 
<p><strong><span style="color: #0000ff;">Method 2:</span></strong></p> 
<p class="p1">Call Context’s <span style="color: #008000;"><b>openFileOutput()</b></span> method to get <span style="color: #0000ff;"><b>FileOutputStream</b></span> object.</p> 
 
 
 
<p class="p1">This method takes two parameters, The first parameter is the <span style="color: #008000;"><strong>file</strong></span> name and the second parameter’s value can be:</p> 
 
 
 
<ol class="ol1 wp-block-list"> 
<li class="li1"><span style="color: #0000ff;"><b>Context.MODE_PRIVATE</b></span> : 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.</li> 
<li class="li1"><span style="color: #0000ff;"><b>Context.MODE_APPEND</b></span> : This mode will append data to the existing file. If not exist it will create a new one.</li> 
</ol> 
 
 
 
<pre class="wp-block-preformatted">FileOutputStream fileOutputStream = getApplicationContext().openFileOutput(fileName, Context.MODE_PRIVATE);<br />OutputStreamWriter outputStreamWriter = new OutputStreamWriter(fileOutputStream);<br />BufferedWriter bufferedWriter = new BufferedWriter(outputStreamWriter); <br />bufferedWriter.write(data);</pre> 
 
 
 
<h4 class="wp-block-heading"><strong><span style="color: #0000ff;">Write File to cache Folder</span></strong></h4> 
 
 
 
<p class="p1">Use <span style="color: #008000;"><b>getCacheDir()</b></span> to get cache folder.</p> 
 
 
 
<pre class="wp-block-preformatted">File file = new File(getCacheDir(), fileName); 
FileOutputStream fileOutputStream = new FileOutputStream(file);</pre> 
 
 
 
<h4 class="wp-block-heading"><strong><span style="color: #000080;">Reading Files from Internal Storage</span></strong></h4> 
 
 
 
<p class="p1">To read a file from the internal storage of the device, the <span style="color: #0000ff;"><b>java.io</b></span> package offers <span style="color: #008000;"><b>openFileInput()</b></span> method which returns the instance of <span style="color: #008000;"><b>FileInputStream</b></span> class. To read the data from file call the <b><span style="color: #008000;">BufferedReader().readLine()</span>.</b></p> 
 
 
 
<h4 class="wp-block-heading"><strong><span style="color: #0000ff;">Read File from files Folder</span></strong></h4> 
 
 
 
<pre class="wp-block-preformatted">FileInputStream fileInputStream = getApplicationContext().openFileInput(fileName); 
InputStreamReader inputStreamReader = new InputStreamReader(fileInputStream); 
BufferedReader bufferedReader = new BufferedReader(inputStreamReader); 
String lineData = bufferedReader.readLine();</pre> 
 
 
 
<h4 class="wp-block-heading"><strong><span style="color: #0000ff;">Read File from cache Folder</span></strong></h4> 
 
 
 
<pre class="wp-block-preformatted">File file = new File(getCacheDir(),fileName); 
FileInputStream fileInputStream = new FileInputStream(file);</pre> 
 
 
 
<h4 class="wp-block-heading"><span style="color: #000080;"><strong>Creating new project</strong></span></h4> 
 
 
 
<p>Create a new project by going to <span style="color: #008000;"><b>File </b><span class="s1"><b>⇒</b></span></span><b><span style="color: #008000;"> New Android Project</span>,</b> select<span style="color: #008000;"> <strong>Empty Activity</strong></span>, provide <span style="color: #008000;"><strong>app name</strong></span>, select language to <span style="color: #0000ff;"><strong>java </strong></span>and then finally click on <span style="color: #008000;"><strong>finish</strong></span>.</p> 
 
 
 
<h4 class="wp-block-heading"><span style="color: #000080;"><strong>Creating the XML file</strong></span></h4> 
 
 
 
<p>The below layout file consist of one <strong><span style="color: #008000;">EditText</span></strong> and four buttons with label text <span style="color: #008000;"><strong>WRITE TO FILE</strong>, <strong>READ FROM FILE</strong>, <strong>CREATE CACHED FILE</strong> <span style="color: #000000;">and </span></span><strong><span style="color: #008000;">READ CACHED FILE</span>.</strong></p> 
 
 
 
<p><strong><span style="color: #0000ff;">activity_main.xml</span></strong></p> 
 
 
 
<pre class="wp-block-preformatted"><;?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>;</pre> 
 
 
 
<h4 class="wp-block-heading"><span style="color: #000080;"><strong>Implementing code in Activity</strong></span></h4> 
 
 
 
<p>Here on click of each button perform different operation:</p>
<!-- WP QUADS Content Ad Plugin v. 2.0.98.1 -->
<div class="quads-location quads-ad2" id="quads-ad2" style="float:none;margin:0px;">

</div>
 
 
 
 
<ul class="wp-block-list"> 
<li><span style="color: #0000ff;"><strong>WRITE TO FILE: </strong><span style="color: #003300;">writes to a file &#8220;<strong><span style="color: #008000;">User&#8221;</span></strong> created inside the <strong><span style="color: #008000;">files</span></strong> folder.</span></span></li> 
<li><span style="color: #0000ff;"><strong>READ FROM FILE:</strong> <span style="color: #000000;">reads from the <span style="color: #003300;">&#8220;<strong><span style="color: #008000;">User&#8221;</span></strong> </span> file.</span></span></li> 
<li><span style="color: #0000ff;"><strong>CREATE CACHED FILE: </strong><span style="color: #003300;">writes to a cache file &#8220;<strong><span style="color: #008000;">UserCache&#8221;</span></strong> created inside the <strong><span style="color: #008000;">cache</span></strong> folder.</span></span></li> 
<li><span style="color: #0000ff;"><strong>READ CACHED FILE: </strong><span style="color: #000000;">reads from <strong><span style="color: #008000;">&#8220;</span><span style="color: #008000;">UserCache&#8221;</span></strong> file.</span></span></li> 
</ul> 
 
 
 
<p><strong><span style="color: #0000ff;">MainActivity.java</span></strong></p> 
 
 
 
<pre class="wp-block-preformatted">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";<br /> 
<strong><span style="color: #008000;"> //write to internal file</span></strong> 
 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); 
 } 
 
 } 
 } 
 }); 
 
<strong><span style="color: #008000;"> //read from internal file</span></strong> 
 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); 
 } 
 } 
 }); 
 
<span style="color: #008000;"><strong> //write to internal cache file</strong></span> 
 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(); 
 } 
 } 
 }); 
 
<span style="color: #008000;"><strong> //read from cache file</strong></span> 
 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); 
 } 
 } 
 }); 
 }<br /> 
<span style="color: #008000;"><strong> //getting views by its id</strong></span> 
 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); 
 } 
 
 <span style="color: #008000;"><strong> // This method will write data to file.</strong></span> 
 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); 
 } 
 } 
 
 <strong><span style="color: #008000;">// This method will write data to FileOutputStream.</span></strong> 
 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); 
 } 
 
 } 
 
<span style="color: #008000;"><strong> //This method will read data from FileInputStream</strong> </span> 
 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(); 
 } 
 } 
}</pre> 
 
 
 
<p>When you run the app it will look like this:</p> 
<p><span style="color: #0000ff;"><strong>Write to/read from a file in the files folder:</strong></span></p> 
<p><img class="alignnone wp-image-2775" src="https://c1ctech.com/wp-content/uploads/2021/08/Screenshot_1630079855-576x1024.png" alt="" width="333" height="592" /> <img class="alignnone wp-image-2776" src="https://c1ctech.com/wp-content/uploads/2021/08/Screenshot_1630080076-576x1024.png" alt="" width="334" height="594" /></p> 
<p><span style="color: #0000ff;"><strong>Write to/read from a file in the cache folder:</strong></span></p> 
<p><img class="alignnone wp-image-2777" src="https://c1ctech.com/wp-content/uploads/2021/08/Screenshot_1630080103-576x1024.png" alt="" width="338" height="601" /> <img class="alignnone wp-image-2778" src="https://c1ctech.com/wp-content/uploads/2021/08/Screenshot_1630080109-576x1024.png" alt="" width="338" height="601" />

