Desarrollo de Android para acceder a archivos en el área de almacenamiento interno y almacenar archivos en el área de almacenamiento externo

almacenamiento de datos

Android utiliza un sistema de archivos similar a los sistemas de archivos basados ​​en disco que se encuentran en otras plataformas. El sistema le ofrece varias opciones para guardar los datos de la aplicación:

Espacio de almacenamiento específico de la aplicación:

Almacene archivos utilizados solo por la aplicación, que se pueden almacenar en un directorio dedicado en el volumen de almacenamiento interno o en otros directorios dedicados en el espacio de almacenamiento externo. Use un directorio en el almacenamiento interno para almacenar información confidencial a la que otras aplicaciones no deberían tener acceso.

almacenamiento compartido:

Almacena archivos que su aplicación intenta compartir con otras aplicaciones, incluidos medios, documentos y otros archivos.

Preferencias:

Almacene datos sin procesar privados en forma de pares clave-valor.

base de datos

: use una biblioteca de persistencia para almacenar datos estructurados en una base de datos dedicada.

Elija almacenamiento interno o externo

Todos los dispositivos Android tienen dos áreas de almacenamiento físico: "interno" y "externo". Estos nombres provienen de los primeros días de Android, cuando la mayoría de los dispositivos proporcionaban memoria no volátil integrada (almacenamiento interno), además de un medio de almacenamiento extraíble, como una tarjeta SD (almacenamiento externo). Algunos dispositivos dividen el espacio de almacenamiento persistente en particiones internas y externas, por lo que incluso si no hay un medio de almacenamiento extraíble, hay dos espacios de almacenamiento y el comportamiento de la API de la partición correspondiente es consistente, sea extraíble o no. En la mayoría de los dispositivos, el almacenamiento interno es más pequeño que el almacenamiento externo. Sin embargo, el almacenamiento interno siempre está disponible en todos los dispositivos, por lo que es más confiable para almacenar los datos de los que dependen sus aplicaciones.

Ingrese el nombre del archivo y el contenido del archivo para acceder al archivo en el área de almacenamiento interno y almacenar el archivo en el área de almacenamiento externo, respectivamente.

diseño de estilo

actividad_guardararchivo.xml

inserte la descripción de la imagen aquí

<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal"
        android:layout_marginTop="30dp">

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="文件名字:"
            android:layout_marginLeft="20dp"
            android:textSize="20dp"></TextView>
        <EditText
            android:id="@+id/et_filename"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginRight="20dp"
            android:layout_marginLeft="80dp"
            android:textSize="20dp"></EditText>
    </LinearLayout>
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="30dp">
        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginLeft="20dp"
            android:text="文件内容:"
            android:textSize="20dp"></TextView>
        <EditText
            android:id="@+id/et_content"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginRight="20dp"
            android:layout_marginLeft="80dp"
            android:textSize="20dp"></EditText>
    </LinearLayout>
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="10dp">

        <Button
            android:id="@+id/btn_saveInternal"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:layout_marginLeft="20dp"
            android:text="存入INTERNAL文件"
            android:textColor="#020202"
            android:textSize="15dp"
            app:backgroundTint="#CFCECE"></Button>

        <Button
            android:id="@+id/btn_saveExternal"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginLeft="20dp"
            android:layout_marginRight="20dp"
            android:layout_weight="1"
            android:text="存入EXTWRNAL文件"
            android:textColor="#020202"
            android:textSize="15dp"
            app:backgroundTint="#CFCECE"></Button>
    </LinearLayout>
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="10dp">

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Internal文件内容:"
            android:layout_marginLeft="20dp"
            android:textSize="20dp"></TextView>
        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginRight="20dp"
            android:layout_marginLeft="20dp"
            android:id="@+id/tv_showInternalContent"
            android:textSize="20dp"></TextView>
    </LinearLayout>
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="60dp">
        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginLeft="20dp"
            android:text="External文件内容:"
            android:textSize="20dp"></TextView>
        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginRight="20dp"
            android:layout_marginLeft="20dp"
            android:id="@+id/tv_showExternalContent"
            android:textSize="20dp"></TextView>
    </LinearLayout>
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="10dp">

        <Button
            android:id="@+id/btn_getInternal"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:layout_marginLeft="20dp"
            android:text="从INTERNA取L文件"
            android:textSize="15dp"
            android:textColor="#020202"
            app:backgroundTint="#CFCECE"></Button>

        <Button
            android:id="@+id/btn_getExternal"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:layout_marginRight="20dp"
            android:layout_marginLeft="20dp"
            android:text="从EXTWRNAL取文件"
            android:textColor="#020202"
            android:textSize="15dp"
            app:backgroundTint="#CFCECE"></Button>
    </LinearLayout>
</LinearLayout>

guardar en archivo

Almacenamiento y recuperación de archivos

package com.example.myapplication4;
import android.Manifest;
import android.content.Context;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.os.Environment;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
public class SaveInFile extends AppCompatActivity implements View.OnClickListener {
    
    
    private EditText et_name;
    private EditText et_content;
    private TextView tv_in_content;
    private TextView tv_ex_content;



    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
    
    

        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_saveinfile);
        et_name = (EditText) findViewById(R.id.et_filename);
        et_content = (EditText) findViewById(R.id.et_content);
        tv_in_content = (TextView) findViewById(R.id.tv_showInternalContent);
        tv_ex_content = (TextView) findViewById(R.id.tv_showExternalContent);
        findViewById(R.id.btn_saveInternal).setOnClickListener(this);
        findViewById(R.id.btn_saveExternal).setOnClickListener(this);
        findViewById(R.id.btn_getInternal).setOnClickListener(this);
        findViewById(R.id.btn_getExternal).setOnClickListener(this);



    }

    public boolean isExternalStorageWritable() {
    
    
        if (Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState())) {
    
    
            return true;
        }
        return false;
    }

    @Override
    public void onClick(View v) {
    
    
        switch (v.getId()) {
    
    
            case R.id.btn_saveInternal:
                FileOutputStream fos;
                try {
    
    
                    fos = openFileOutput(et_name.getText().toString().trim(), Context.MODE_PRIVATE);
                    fos.write(et_content.getText().toString().trim().getBytes());
                    fos.close();
                    Toast.makeText(this, "存入内部成功", Toast.LENGTH_SHORT).show();
                } catch (FileNotFoundException e) {
    
    
                    e.printStackTrace();
                } catch (IOException e) {
    
    
                    e.printStackTrace();
                }
                break;
            case R.id.btn_saveExternal:
                if (isExternalStorageWritable()) {
    
    
                    File file = new File(Environment.getExternalStorageDirectory(), et_name.getText().toString().trim() + ".txt");
                    fos = null;
                    try {
    
    
                        fos = new FileOutputStream(file);
                        fos.write(et_content.getText().toString().trim().getBytes());
                        Toast.makeText(this, "创建成功", Toast.LENGTH_SHORT).show();
                    } catch (FileNotFoundException e) {
    
    
                        Toast.makeText(this, "请允许\"SavelInFile\"访问您设备上的照片、\n" +
                                "媒体内容和文件\n", Toast.LENGTH_LONG).show();
                        e.printStackTrace();
                    } catch (IOException e) {
    
    
                        e.printStackTrace();
                    }
                } else {
    
    
                    Toast.makeText(this, "外部存储区不可用", Toast.LENGTH_SHORT).show();
                }
                break;


            case R.id.btn_getInternal:
                FileInputStream fis;
                try {
    
    
                    fis = openFileInput(et_name.getText().toString().trim());
                    byte[] buffer = new byte[fis.available()];
                    fis.read(buffer);
                    tv_in_content.setText(getFilesDir() + "/" + et_name.getText().toString().trim() + ".txt" + ":" + new String(buffer));
                    fis.close();
                    Toast.makeText(this, "从内部读取成功", Toast.LENGTH_SHORT).show();
                } catch (FileNotFoundException e) {
    
    
                    e.printStackTrace();
                } catch (IOException e) {
    
    
                    e.printStackTrace();
                }

                break;

            case R.id.btn_getExternal:
                File file = new File(Environment.getExternalStorageDirectory(), et_name.getText().toString().trim() + ".txt");
                try {
    
    
                    fis = new FileInputStream(file);
                    byte[] buffer = new byte[fis.available()];
                    fis.read(buffer);
                    tv_ex_content.setText(Environment.getExternalStorageDirectory().getPath() + "/" + et_name.getText().toString().trim() + ".txt" + ":" + new String(buffer));
                    Toast.makeText(this, "从外部读取成功", Toast.LENGTH_SHORT).show();
                    fis.close();
                } catch (FileNotFoundException e) {
    
    
                    e.printStackTrace();
                } catch (IOException e) {
    
    
                    e.printStackTrace();
                }

                break;

        }

    }


}

Resultados experimentales

Acceder a archivos en el área de almacenamiento interno

inserte la descripción de la imagen aquí

Almacenar archivos en almacenamiento externo

inserte la descripción de la imagen aquí

Supongo que te gusta

Origin blog.csdn.net/qq_46556714/article/details/126580453
Recomendado
Clasificación