SoFunction
Updated on 2025-04-10

How to use files for data storage on Android

This article describes the method of Android using files for data storage. Share it for your reference. The details are as follows:

Many times the software we develop requiresStore processed data for re-access. Android provides the following ways for data storage:

document

SharedPreferences(parameters)
SQLite database
Content provider

network

First of all, let me introduce it to youHow to store data using files

Activity provides the openFileOutput() method that can be used to output data to a file. The specific implementation process is the same as saving data to a file in a J2SE environment.

public class FileActivity extends Activity {
 @Override
 public void onCreate(Bundle savedInstanceState) {  
   FileOutputStream outStream = ("", Context.MODE_PRIVATE);
   ("My name is Lin Jiqin".getBytes());
   (); 
 }
} 

Detailed explanation of openFileOutput(fileName, mode) method:

First parameter:

Used to specify file name, cannot contain the path separator "/". If the file does not exist, Android will automatically create it. The created file is saved in the /data/data/<packagename>/files directory, such as: /data/data//files/ , by clicking the MyEclipse menu "Window"-"Show View"-"Other",
Expand the Android folder in the dialog window, select the File Explorer view below, and then expand the /data/data/<package name>/files directory in the File Explorer view to see the file

Second parameter:

Used to specify operation modes, there are four modes
Context.MODE_PRIVATE  = 0
The default operation mode means that the file is private data and can only be accessed by the application itself. In this mode, the written content will overwrite the content of the original file. If you want to append the newly written content to the original file.
Context.MODE_APPEND can be used.
Context.MODE_APPEND  = 32768
Check whether the file exists. If it exists, add content to the file, otherwise create a new file.
Context.MODE_WORLD_READABLE = 1
Indicates that the current file can be read by other applications
Context.MODE_WORLD_WRITEABLE = 2
Indicates that the current file can be written to by other applications

Notice:

Context.MODE_WORLD_READABLE and Context.MODE_WORLD_WRITEABLE are used to control whether other applications have permission to read and write the file.
If you want the file to be read and written by other applications, you can pass it in: openFileOutput("", Context.MODE_WORLD_READABLE + Context.MODE_WORLD_WRITEABLE);
Android has its own security model. When the application (.apk) is installed, the system will assign it a userid. When the application wants to access other resources such as files, the userid needs to match. By default, any file created by the application, sharedpreferences, and databases should be private (located in /data/data/<package name>/files) and cannot be accessed by other programs. Unless Context.MODE_WORLD_READABLE or Context.MODE_WORLD_WRITEABLE is specified at creation time, only in this way other programs can access it correctly.
If you want to open a file stored in the /data/data/<package name>/files directory application privately, you can use Activity to provide the openFileInput() method.
FileInputStream inStream = ().openFileInput("");
Or use the absolute path to the file directly:
File file = new File("/data/data//files/");
FileInputStream inStream = new FileInputStream(file);
Note: The "" in the file path above is the package where the application is located. When you write the code, you should replace it with the package that you use for your own application.
For private files, they can only be accessed by applications that create the file. If you want the file to be read and written by other applications, you can create the file.
Specify the Context.MODE_WORLD_READABLE and Context.MODE_WORLD_WRITEABLE permissions.
Activity also provides getCacheDir() and getFilesDir() methods:
getCacheDir() method is used to get /data/data/<package name>/cache directory
getFilesDir() method is used to get /data/data/<package name>/files directory

Case

FileService class: file access operation class

package ;
import ;
import ;
import ;
public class FileService {
 /**
   * Save data
   *
   * @param outputStream
   * @param content
   * @throws Exception
   */
 public static void save(OutputStream outputStream, String content) throws Exception {
  (());
  ();
 }
 /**
   * Read data
   *
   * @param inputStream
   * @return
   * @throws Exception
   */
 public static String read(InputStream inputStream) throws Exception {
  // Write data into memory  ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); 
  // Buffer  byte[] buffer = new byte[1024]; 
  int len = -1;
  while ((len = (buffer)) != -1) {
   (buffer, 0, len);
  }
  //Storage data  byte[] data = (); 
  ();
  ();
  return new String(data);
 }
}

FileServiceTest test class:

package ;
import ;
import ;
import ;
import ;
import ;
/**
  * android test
  *
  * @author jiqinlin
  *
  */
public class FileServiceTest extends AndroidTestCase {
 private final String TAG = "FileServiceTest"; 
 public void testSave() throws Exception{
  OutputStream outputStream = ().openFileOutput("", Context.MODE_PRIVATE);
  (outputStream, "abc");
 }
 public void testRead() throws Exception{
  InputStream inputStream= ().openFileInput("");
  String content = (inputStream);
  (TAG, content);
 }
}

List file:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:andro
  package=""
  android:versionCode="1"
  android:versionName="1.0">
 <application android:icon="@drawable/icon" android:label="@string/app_name">
  <uses-library android:name="" />
  <activity android:name=".FileActivity"
     android:label="@string/app_name">
   <intent-filter>
    <action android:name="" />
    <category android:name="" />
   </intent-filter>
  </activity>
 </application>
 <uses-sdk android:minSdkVersion="7" />
 <instrumentation android:name=""
   android:targetPackage="" android:label="Tests for My App" />
</manifest> 

I hope this article will be helpful to everyone's Android programming design.