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

前言

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




    

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包名目录下
Android文件的保存与读取(SD Card 中以及包名目录下)_第1张图片

效果

SD card 操作成功后
Android文件的保存与读取(SD Card 中以及包名目录下)_第2张图片

项目地址:
链接:https://pan.baidu.com/s/1q9FPhjFvoZHSG2854FIvyg 密码:9fxc

你可能感兴趣的:(Android文件的保存与读取(SD Card 中以及包名目录下))