android I/0 stream operation file (file storage)

file store

The file storage method is not limited by type. Some data can be saved directly in the device in the form of files, such as text files, PDF, audio, pictures, etc. When storing complex types of data, file storage is usually used. Java provides a complete set of I/ О Flow system, through I/ О Streaming can easily access files on disk. Similarly, Android also supports I/O streaming to access files stored in mobile devices such as mobile phones.

Stream file 0 / I

Conduct I/ О When operating a file with stream, you need to obtain the input stream and output stream of the file first. In Android applications, the input stream and output stream of files can be obtained through openFileInput() and openFileOuput() methods provided by the Context object. The details of these two methods are as follows.

  • FilelnputStream openFileInput(String name): used to obtain the standard file input stream with the specified name file name under the data folder of the application, so as to read the files in the device.
  • FileOutputStream openFileOuput(String name, int mode): used to obtain the standard file output stream with the specified name file name under the data folder of the application, so as to write data to the file of the device.

The second parameter mode of the openFileOutput() method is used to specify the mode of the output stream, that is, the mode of opening the file for operation. Four static constants are provided in the Context class to represent different output modes, as shown in the following table.

4 file read / write modes

patternFunction description
Context.MODE_PRIVATEPrivate mode. The files created by this mode are private files and can only be accessed by the application itself. Therefore, the contents written in this mode will overwrite the contents of the original file
Context. MODE_APPENDAttach mode, which will first check whether the file exists. If the file does not exist, a new file will be created; If the file exists, add content at the end of the original file
Context.MODE_WORLD_READABLEReadable mode, whose files can be read by other applications
Context.MODE_WORLD_WRITABLEWritable mode. Files in this mode can be read and written by other applications

In addition, the Context object also provides some methods to access the data folder of the application, as shown in the following table.
Methods of accessing data folders

methodFunction description
File getDir(String name, int mode)Get or create the subdirectory corresponding to name under the data folder of the application
File getFilesDir()Gets the absolute path of the application's data folder
String[] fileList()Returns all files in the application's data folder
boolean deleteFile( String name)Delete the specified file under the application's data folder

The following code demonstrates how to use I/O flow to read and write files
Create xml layout file

The xml layout code is as follows

<?xml version="1.0" encoding="utf-8"?>
<!-- Linear layout, width and height adapt to screen changes, and the horizontal direction is vertical -->
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">
    <!-- Edit the input box. The width adapts to the linear layout change and the height adapts to itself. Set the number of display lines to four -->
    <EditText
        android:id="@+id/ediFileOut"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:lines="4"/>
    <!-- Save file button, width and height adapt to yourself, and the button text is displayed-->
    <Button
        android:id="@+id/btnWrite"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Save file"/>
    <!-- Edit the display box. The width adapts to the change of linear layout and the height adapts to itself. Set the cursor invisible and non editable. The number of lines is 4-->
    <EditText
        android:id="@+id/editFileIn"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:cursorVisible="false"
        android:editable="false"
        android:lines="4"/>
    <!-- The width and height of the read file button adapt to itself, and the button text is displayed-->
    <Button
        android:id="@+id/btnRead"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="read file"/>
</LinearLayout>

The layout of the above interface is relatively simple. It only contains two text boxes and two buttons, which are used for saving and reading files respectively.

Then create the Activity program

The activity code is as follows

package com.example.wenjiancuncu;

import android.content.Context;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.PrintStream;

public class FileIOActivity extends AppCompatActivity {
    private EditText editFileIn, editFileOut; //Declare two text boxes
    private Button btnRead, btnWrite; //Declare two buttons
    final String FILE_NAME = "qstIO.txt"; //specify a filename
    @Override //Override parent method
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState); //Call parent method
        setContentView(R.layout.activity_file_io); //Set layout
        //Get two text boxes
        editFileIn = (EditText) findViewById(R.id.editFileIn);
        editFileOut = (EditText) findViewById(R.id.ediFileOut);
        //Get two buttons
        Button btnRead = (Button) findViewById(R.id.btnRead);
        Button btnWrite = (Button) findViewById(R.id.btnWrite);
        //Set the event listener of btnRead button as an anonymous class
        btnRead.setOnClickListener(new View.OnClickListener() {
            @Override //Rewrite interface method
            public void onClick(View v) {
                //Read the contents of the specified file and display it in the edit file in text box
                editFileIn.setText(read());
            }
        });
        //Set the event listener of btnWrite button as an anonymous class
        btnWrite.setOnClickListener(new View.OnClickListener() {
            @Override //Rewrite interface method
            public void onClick(View v) {
                write(editFileOut.getText().toString()); //Write the contents of editFileOut to the file
                editFileOut.setText(""); //Clear the contents of the editFileOut text box
            }
        });
    }
    private String read() {
        try {
            FileInputStream fis = openFileInput(FILE_NAME); //Open file input stream
            byte[] buff = new byte[1024]; //Define a byte cache array
            int hasRead = 0;
            StringBuilder sb = new StringBuilder(""); //Create variable string
            //Read file contents
            while ((hasRead = fis.read(buff)) > 0) {
                //Converts a byte array into a string and adds it to a variable string
                sb.append(new String(buff, 0, hasRead));
            }
            fis.close(); //Close file input stream
            return sb.toString(); //Returns a string
        }catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
    private void write(String content) {
        try {
            //Open file output stream in append mode
            FileOutputStream fos = openFileOutput(FILE_NAME, Context.MODE_APPEND);
            PrintStream ps = new PrintStream(fos); //Wrap FileOutStream into PrintStream
            ps.println(content); //Output file content
            ps.close(); //Close file output stream
            //Use Toast to display successful saving
            Toast.makeText(FileIOActivity.this,"Saved successfully", Toast.LENGTH_LONG).show();
        }catch (Exception e) {
            e.printStackTrace();
        }
    }
}

The core operation of the above code is to save and read files. read() and write() methods are used to read and write files respectively; In the code, event listeners are set on the btnRead and btnWrite buttons respectively, and the corresponding read() or write() method is invoked in the event processing method to realize the reading or saving of the files.

Declare Activity in AndroidMainfest

Operation results

The data files of Android applications are saved in / data/data / package name / files directory by default. In the File Explorer tab of Android device monitor, expand / data/data/com Package name / files directory, where you can see the saved qstio Txt data file, as shown in the figure below.



Keywords: Android

Added by magic-chef on Tue, 08 Feb 2022 09:01:09 +0200