[JAVA] * Android * Saving / loading files to internal storage

Introduction

Hello. I will start writing articles today. I plan to use Qiita as a programming memo. I have been using Android for about 2 years. I am a graduate student who will start working next year.

This time, I will explain how to save and load files in Android's internal storage. The content of each article about Android storage is slightly different, and I think that some people may get lost, so I will write a standard one.

Premise

The development environment is as follows. *Android Studio 4.0.1 *targetSdkVersion 28 *Google Nexus 5x

Internal storage and external storage

Android has internal storage and external storage.

■ Internal storage

■ External storage

There are the following three types of storage used for storage.

Each storage is saved in the following in the structure of Device File Explorer of Android Studio.

Save the file to internal storage

To save a file, get an instance of `FileOutputStream``` using the ```openFileOutput ()` method. This will allow you to open the stream. Also, if you use ```openFileOutput () `` `, the path will be automatically acquired and saved even if you do not specify the path of the internal storage.

FileOutputStream fileOutputstream = openFileOutput("text.txt", Context.MODE_PRIVATE);

** First argument ** "/path/file name"

** Second argument **

value Description
MODE_WORLD_READABLE Can be referenced from other apps
MODE_WORLD_WRITEABLE Can be written from other apps
MODE_PRIVATE Not accessible from other apps
MODE_APPEND If there is a file, add it

Also, if you want to specify multiple modes, you can specify multiple modes by connecting pipes. mode_private | mode_append

After that, convert the character string you want to write to the file to a byte type array and write it to the stream using `write ()`.

fileOutputStream.write(str.getBytes());

Read a file from storage

To read a file, get an instance of `FileInputStream``` using the ```openFileInput ()` method. This will allow you to open the stream.

FileInputStream fileInputStream = openFileInput("text.txt");

inputstreamreaderReads a byte from the stream and decodes it to the specified character. ItbufferedreaderPut it in and read it line by line. To increase conversion efficiencybufferedreaderInsideinputstreamreaderIt seems good to wrap.

BufferedReader reader = new BufferedReader(new InputStreamReader(fileInputStream, "UTF-8"));
String lineBuffer;
while (true){
    lineBuffer = reader.readLine();
    if (lineBuffer != null){
        text += lineBuffer;
    }
    else {
        break;
    }
}

Sample code

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.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"
    tools:context=".MainActivity">
    <Button
        android:id="@+id/button1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginStart="50dp"
        android:layout_marginTop="100dp"
        android:text="Save File"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />
    <Button
        android:id="@+id/button2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginStart="100dp"
        android:layout_marginTop="100dp"
        android:text="Read File"
        app:layout_constraintStart_toEndOf="@+id/button1"
        app:layout_constraintTop_toTopOf="parent" />
    <TextView
        android:id="@+id/textView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="120dp"
        android:text=""
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/editText" />
    <EditText
        android:id="@+id/editText"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="30dp"
        android:ems="10"
        android:inputType="textPersonName"
        android:text="Name"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />
</android.support.constraint.ConstraintLayout>

MainActivity.java

package com.example.keita.myapplication;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;

public class MainActivity extends AppCompatActivity {
    private TextView textView;
    private Button button1;
    private Button button2;
    private EditText editText;
    private String fileName = "test.txt";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        this.textView = findViewById(R.id.textView);
        this.editText = findViewById(R.id.editText);
        this.button1 = findViewById(R.id.button1);
        this.button2 = findViewById(R.id.button2);
        this.button1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String text = editText.getText().toString();
                saveFile(fileName, text);
            }
        });
        this.button2.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String str = readFile(fileName);
                textView.setText(str);
            }
        });
    }


    private void saveFile(String file, String str){
        try {
            FileOutputStream fileOutputStream = openFileOutput(file, MODE_PRIVATE | MODE_APPEND);
            fileOutputStream.write(str.getBytes());
        } catch (IOException e) {
            e.printStackTrace();
        }
    }


    private String readFile(String file){
        String text = null;
        try {
            FileInputStream fileInputStream = openFileInput(file);
            BufferedReader reader = new BufferedReader(new InputStreamReader(fileInputStream, "UTF-8"));
            String lineBuffer;
            while (true){
                lineBuffer = reader.readLine();
                if (lineBuffer != null){
                    text += lineBuffer;
                }
                else {
                    break;
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return text;
    }
}

Recommended Posts

* Android * Saving / loading files to internal storage
* Android * Saving / loading images to external storage
* Android * About saving / reading files to external storage and permissions
Zip and upload multiple files to Firebase Storage on Android.
Android-Upload image files to Azure Blob Storage in Java
[Rails 6] Add images to seed files (using Active Storage)
Add files to jar files
Introduction to JAR files
Introduction to Android Layout
[Rails] Create API to download files with Active Storage [S3]