Android文件的保存与读取(SD Card 中以及包名目录下)

前言

android 6.0 以后需要危险权限的请求
权限

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 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"
    android:orientation="vertical"
    tools:context=".file.ReadFileActivity">

    <Button
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="@string/read_file_resource"
        android:onClick="readFileResource"/>
    <Button
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="@string/save_file_data"
        android:onClick="saveFileDataResource"/>
    <Button
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="@string/read_file_data"
        android:onClick="readFileDataResource"/>

    <Button
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="@string/save_file_sdcard"
        android:onClick="saveFileSdcardResource"/>
    <Button
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="@string/read_file_sdcard"
        android:onClick="readFileSdcardResource"/>

    <TextView
        android:id="@+id/tv_show_data"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />

</LinearLayout>

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

import android.Manifest;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.os.Environment;
import android.text.method.ScrollingMovementMethod;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;

import com.thomas.android.base.R;
import com.thomas.tool.utility.ConvertUtils;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintStream;
import java.util.Scanner;


public class ReadFileActivity extends AppCompatActivity {
    private String FILE_NAME = "user.txt";
    private TextView tv_show_data;
    private StringBuilder stringBuilder = new StringBuilder();
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_read_file);
        tv_show_data = findViewById(R.id.tv_show_data);
        tv_show_data.setMovementMethod(ScrollingMovementMethod.getInstance());
        initPermission();
    }

    private void initPermission() {
        if (ActivityCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
            String[] permission = new String[]{
                    Manifest.permission.WRITE_EXTERNAL_STORAGE,Manifest.permission.READ_EXTERNAL_STORAGE
            };
            ActivityCompat.requestPermissions(this,permission,1);
        }else {
            createFolderAndFile();
        }
    }


    /**
     * create folder and file where you like
     * data/data/package name/
     * sdcard
     */
    private void createFolderAndFile() {
        // sdCard is exist
        boolean sdcardExist = Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED);
        String pathName;
        if (sdcardExist){
            // get sdcard folder has two way
            //String pathName = "/mnt/sdcard" + File.separator + "ReadFile/";
            pathName =  Environment.getExternalStorageDirectory().getAbsolutePath() + File.separator + "ReadFile";
        }else {
            // below data folder
             pathName = "data" + Environment.getDataDirectory().getAbsolutePath() + File.separator + getPackageName()+ File.separator + "ReadFile";
        }
        createFolder(pathName);
        createFile(pathName);
    }


    private void createFolder(String pathName) {
        File file = new File(pathName);
        if (!file.exists()){
            if (file.mkdir()){
                System.out.println("create folder success");
            }else {
                System.out.println("create folder failed ");
            }
        }
    }

    /**
     * create file below folder
     */
    private void createFile(String pathName) {
        File includeSubFile = new File(pathName,"thomas.txt");
        if (!includeSubFile.exists()){
            try {
                if (includeSubFile.createNewFile()){
                    System.out.println("create folder success");
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    public void readFileResource(View view) {
        stringBuilder.setLength(0);
        InputStream inputStream = getResources().openRawResource(R.raw.my_book);
        Scanner scanner = new Scanner(inputStream);
        while (scanner.hasNext()){
            stringBuilder.append(scanner.next()).append("\n");
        }
        scanner.close();
        try {
            inputStream.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        tv_show_data.setText(stringBuilder.toString());

    }

    public void saveFileDataResource(View view) {
        try {
            FileOutputStream outputStream = openFileOutput(FILE_NAME,MODE_PRIVATE);
            PrintStream printStream = new PrintStream(outputStream);
            printStream.println("name:jack");
            printStream.println("age:20");
            printStream.close();
            Toast.makeText(this,R.string.save_success,Toast.LENGTH_SHORT).show();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
    }

    public void readFileDataResource(View view) {
        stringBuilder.setLength(0);
        try {
            FileInputStream fileInputStream = openFileInput(FILE_NAME);
            Scanner scanner = new Scanner(fileInputStream);
            while (scanner.hasNext()){
                stringBuilder.append(scanner.next()).append("\n");
            }
            tv_show_data.setText(stringBuilder.toString());
            scanner.close();
            try {
                fileInputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        } catch (FileNotFoundException e) {
            // file not found to do
            Toast.makeText(this,e.getMessage(),Toast.LENGTH_SHORT).show();
        }

    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED){
            createFolderAndFile();
        }

    }

    public void saveFileSdcardResource(View view) {
        boolean sdcardExist = Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED);
        String pathName;
        if (sdcardExist){
            pathName =  Environment.getExternalStorageDirectory().getAbsolutePath() + File.separator + "ReadFile";
        }else {
            pathName = "data" + Environment.getDataDirectory().getAbsolutePath() + File.separator + getPackageName()+ File.separator + "ReadFile";
        }
        File file = new File(pathName,"thomas.txt");
        try {
            FileOutputStream fileOutputStream = new FileOutputStream(file);
            try {
                String data = ConvertUtils.getAssets(getAssets().open("image.json"));
                try {
                    fileOutputStream.write(data.getBytes());
                    fileOutputStream.close();
                    Toast.makeText(this,R.string.save_success,Toast.LENGTH_SHORT).show();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }

        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
    }

    public void readFileSdcardResource(View view) {
        stringBuilder.setLength(0);
        boolean sdcardExist = Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED);
        String pathName;
        if (sdcardExist){
            pathName =  Environment.getExternalStorageDirectory().getAbsolutePath() + File.separator + "ReadFile";
        }else {
            pathName = "data" + Environment.getDataDirectory().getAbsolutePath() + File.separator + getPackageName()+ File.separator + "ReadFile";
        }
        File file = new File(pathName,"thomas.txt");
        try {
            String readLine;
            BufferedReader bufferedReader = new BufferedReader(new FileReader(file));
            try {
                while ((readLine = bufferedReader.readLine() )!= null){
                    stringBuilder.append(readLine);
                }
                tv_show_data.setText(stringBuilder.toString());
            } catch (IOException e) {
                e.printStackTrace();
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
    }
}

创建成功后data包名目录下
在这里插入图片描述

效果
在这里插入图片描述

SD card 操作成功后
在这里插入图片描述
在这里插入图片描述
项目地址:
链接:https://pan.baidu.com/s/1q9FPhjFvoZHSG2854FIvyg 密码:9fxc

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值