Размещение файлов во внешнем хранилище

Последнее обновление: 17.10.2021

В прошлой теме мы рассмотрели сохранение и чтение файлов из каталога приложения. По умолчанию такие файлы доступны только самому приложения. Однако мы можем помещать и работать с файлами из внешнего хранилища приложения. Это также позволит другим программам открывать данные файлы и при необходимости изменять.

Весь механизм работы с файлами будет таким же, как и при работе с хранилищем приложения. Ключевым отличием здесь будет получение и использование пути к внешнему хранилищу через метод getExternalFilesDir() класса Context.

Итак, пусть в файле activity_main.xml будет такая же разметка интерфейса:

<?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"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <EditText
        android:id="@+id/editor"
        android:layout_width="0dp"
        android:layout_height="0dp"
        android:textSize="18sp"
        android:gravity="start"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintBottom_toTopOf="@id/save_text"
        app:layout_constraintTop_toTopOf="parent" />
    <Button
        android:id="@+id/save_text"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"

        android:onClick="saveText"
        android:text="Сохранить"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintBottom_toTopOf="@id/text"
        app:layout_constraintTop_toBottomOf="@id/editor" />

    <TextView
        android:id="@+id/text"
        android:layout_width="0dp"
        android:layout_height="0dp"
        android:gravity="start"
        android:textSize="18sp"

        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintBottom_toTopOf="@+id/open_text"
        app:layout_constraintTop_toBottomOf="@+id/save_text" />
    <Button
        android:id="@+id/open_text"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:onClick="openText"
        android:text="Открыть"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/text" />

</androidx.constraintlayout.widget.ConstraintLayout>

А код класса MainActivity будет выглядеть следующим образом:

package com.example.filesapp;

import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;

public class MainActivity extends AppCompatActivity {

    private final static String FILE_NAME = "document.txt";
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }
    private File getExternalPath() {
        return new File(getExternalFilesDir(null), FILE_NAME);
    }
    // сохранение файла
    public void saveText(View view){

        try(FileOutputStream fos = new FileOutputStream(getExternalPath())) {
            EditText textBox = findViewById(R.id.editor);
            String text = textBox.getText().toString();
            fos.write(text.getBytes());
            Toast.makeText(this, "Файл сохранен", Toast.LENGTH_SHORT).show();
        }
        catch(IOException ex) {

            Toast.makeText(this, ex.getMessage(), Toast.LENGTH_SHORT).show();
        }
    }
    // открытие файла
    public void openText(View view){
        
        TextView textView = findViewById(R.id.text);
        File file = getExternalPath();
        // если файл не существует, выход из метода
        if(!file.exists()) return;
        try(FileInputStream fin =  new FileInputStream(file)) {
            byte[] bytes = new byte[fin.available()];
            fin.read(bytes);
            String text = new String (bytes);
            textView.setText(text);
        }
        catch(IOException ex) {

            Toast.makeText(this, ex.getMessage(), Toast.LENGTH_SHORT).show();
        }
    }
}

С помощью выражения getExternalFilesDir(null) получаем доступ к папке приложения во внешнем хранилище и устанавливаем объект файла:

private File getExternalPath() {
    return new File(getExternalFilesDir(null), FILE_NAME);
}

В качестве параметра передается тип папки, но в данном случае он нам не важен, поэтому передается значение null

Все остальные действия по записи/чтению файла будут такими же, как и в предыдущей теме в случае с работой с локальной папкой файла.

Запись файла во внешнем хранилищ в Android и Java

И после операции записи на смартфоне через Device File Explorer мы сможем увидеть созданный файл в папке storage/self/primary/Android/data/[название_пакета]/files:

Файл во внещнем хранилище в Device File Explorer в Android Studio
Помощь сайту
Юмани:
410011174743222
Перевод на карту
Номер карты:
4048415020898850