English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

Detailed Explanation and Simple Examples of Android File Operations

 Detailed Explanation of Android File Operations

To put it simply, Android's file operations are essentially the handling of Java's file operations. So if you are familiar with Java's io file operations, Android's file operations are a piece of cake. Alright, without further ado, let's get into today's topic.

Let's start with a small project to get a grasp of things.

First is a layout file, which is quite simple, so let's go straight to the code.

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
  xmlns:tools="http://schemas.android.com/tools"
  android:layout_width="match_parent"
  android:layout_height="match_parent"
  android:orientation="vertical" >
  <TextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="文件名称" />
  <EditText 
    android:id="@"+id/et_filename"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:hint="file name"
    />
  <TextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="文件内容" />
  <EditText 
    android:id="@"+id/et_filecontent"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:lines="7"
    android:hint="file content"
    />
  <Button 
    android:id="@"+id/btn_save"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:onClick="toSave"
    android:text="Save"
    />
  <Button 
    android:id="@"+id/btn_get"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:onClick="getFile"
    android:text="Get"
    />
</LinearLayout>

This is the Java file for our main interface. Continuing with the code.

package com.mark.storage;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import com.mark.service.FileService;
public class MainActivity extends Activity {
  private EditText mEt_filename, mEt_filecontent;
  private Button mBtn_save;
  private void init(){
    mEt_filecontent = (EditText) findViewById(R.id.et_filecontent);
    mEt_filename = (EditText) findViewById(R.id.et_filename);
    mBtn_save = (Button) findViewById(R.id.btn_save);
  }
  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    init();
  }
  /**
   * Save data to a file
   * @param view
   */
  public void toSave(View view) {
    String fileName = mEt_filename.getText().toString();
    String fileContent = mEt_filecontent.getText().toString();
    FileService service = new FileService(getApplicationContext());
    boolean isSucceed = service.save(fileName, fileContent);
    if(isSucceed){
      Toast.makeText(getApplicationContext(), "Congratulations, you have successfully saved the file!", Toast.LENGTH_SHORT).show();
    } else {
      Toast.makeText(getApplicationContext(), "Sorry, you failed to save the file!", Toast.LENGTH_SHORT).show();
    }
  }
  public void getFile(View view){
    String fileName = mEt_filename.getText().toString();
    FileService service = new FileService(getApplicationContext());
    String fileContent = service.getFile(fileName);
    if(fileContent != null || !fileContent.equals("")) {
      mEt_filecontent.setText(fileContent);
    } else {
      Toast.makeText(getApplicationContext(), "Sorry, file read failed!", Toast.LENGTH_SHORT).show();
    }
  }
}

Don't you feel a bit strange about the code inside? What is FileService?

In fact, FileService is our business class, mainly responsible for helping us implement operations such as file saving and reading. The code is also attached below.

package com.mark.service;
import java.io.ByteArrayOutputStream;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import android.content.Context;
public class FileService {
  //A class provided by Android that can quickly obtain a file output stream, note that the parameter cannot be a path, but must be a file name.
  private Context mContext;
  public FileService(Context context) {
    this.mContext = context;
  }
  /**
   * A method to save a file
   * @param fileName
   * @param fileContent
   * @return
   */
  public boolean save(String fileName, String fileContent) {
    try {
      //If using Context.MODE_PRIVATE mode, only this application is allowed to access this file, and data is added in a cover-up manner.
      FileOutputStream fos = mContext.openFileOutput(fileName, Context.MODE_PRIVATE);
      fos.write(fileContent.getBytes());
      fos.close();
      return true;
    catch (Exception e) {
      e.printStackTrace();
      return false;
    }
  }
  /**
   * Get detailed information of the file saved before
   * @param fileName
   * @return
   */
  public String getFile(String fileName) {
    String fileContent = "";
    try{
      FileInputStream fis = mContext.openFileInput(fileName);
      byte[] buf = new byte[1024];
      int len;
      ByteArrayOutputStream bais = new ByteArrayOutputStream();
      while((len = fis.read(buf))!= -1{
        bais.write(buf, 0, len);
      }
      byte[] data = bais.toByteArray();
      fileContent = new String(data);
      fis.close();
      return fileContent;
    }
      e.printStackTrace();
      return "Sorry, file read failed!";
    }
  }
}

Analysis of the business class

Now let's get to the point. The core of this small project lies in this business class, for the following reasons:

  1. Context: Android's built-in context class, which is convenient for obtaining file stream objects
  2. In the read file method, the ByteArrayOutputStream class is used, which is very important. If we only use strings to read stored files, we will not be able to get the target data due to serialization issues.
  3. The operation result is 'feedback' using return values, which is convenient for providing users with a friendly interface and experience.

Core

The idea of layering, placing classes with different functions in different packages, which is convenient for program debugging and code maintenance in the future.

Thank you for reading, I hope it can help everyone. Thank you for your support of this site!