data文件和sd卡文件io流读写(学生自用,文章内容有误)

项目场景:

提示::
data文件和sd卡文件读写方法


三个类

data文件读写代码:

import android.content.Context;

import java.io.*;


public class DataFile {
    private Context context;
    /**
     * @param context 一个context
     */
    public DataFile(Context context) {
        this.context = context;
    }

    /**
     * @param path 文件路径:/storage/emulated/0/Android/data/包名/files/path
     * @param content 文件内容
     */
    public void write(String path,String content) {
        try {
            String absolutePath = context.getExternalFilesDir(null).getAbsolutePath();
            File file = new File(absolutePath,path);
            FileOutputStream outputStream = new FileOutputStream(file,true);
            PrintStream printStream = new PrintStream(outputStream);
            printStream.print(content);
            printStream.close();
        } catch (FileNotFoundException e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * @param path 文件路径:/storage/emulated/0/Android/data/包名/files/path
     * @return txt文件的字符串
     */
    public String read(String path) {
        try {
            String absolutePath = context.getExternalFilesDir(null).getAbsolutePath();
            File file = new File(absolutePath,path);
            FileInputStream fileInputStream = new FileInputStream(file);
            byte[] bytes = new byte[1024];
            int len;
            StringBuilder sb = new StringBuilder();
            while ((len = fileInputStream.read(bytes)) > 0) {
                sb.append(new String(bytes, 0, len));
            }
            fileInputStream.close();
            return sb.toString();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
}


sd卡文件读写代码:

import android.os.Environment;
import android.util.Log;

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

/**
 * 必须在build.gradle中的defaultConfig添加targetSdkVersion 24才能成功
 */
public class SDFile {
    /**
     * @param child 路径:/storage/emulated/0/child
     * @param bytes 要写入的字节
     */
    public void write(String child,byte[] bytes) {
        String path = Environment.getExternalStorageDirectory().getPath();
        File file = new File(path, child);
        try {
            FileOutputStream fos = new FileOutputStream(file,true);
            fos.write(bytes);
            fos.close();
            Log.i("","写入成功");
        } catch (IOException e) {
            Log.i("","写入失败");
            e.printStackTrace();
        }
    }

    /**
     * @param child 路径:/storage/emulated/0/child
     * @return txt文件字符串
     */
    public String read(String child) {
        String path = Environment.getExternalStorageDirectory().getPath();
        File file = new File(path, child);
        StringBuilder sb = new StringBuilder();
        try {
            FileInputStream fis = new FileInputStream(file);
            byte[] bytes = new byte[1024];
            int len;
            while ((len = fis.read(bytes)) != -1) {
                sb.append(new String(bytes, 0, len));
                Log.i("","读取成功");
            }
            fis.close();
            return sb.toString();
        } catch (IOException e) {
            Log.i("","读取失败");
            e.printStackTrace();
        }
        return null;
    }
}




动态权限申请代码:

import android.Manifest;
import android.app.Activity;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Build;
import android.provider.Settings;
import androidx.core.content.ContextCompat;

/**
 * 动态请求权限
 */
public class MyPermission {
    private Activity activity;
    private static final int REQUEST_CODE = 0;
    public MyPermission(Activity activity) {
        this.activity = activity;
    }

    /**
     * @return 是否拥有读取数据权限
     */
    public boolean notREAD_EXTERNAL_STORAGE(){
        return ContextCompat.checkSelfPermission(activity, Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED;
    }

    /**
     * @return 是否拥有写入数据权限
     */
    public boolean notWRITE_EXTERNAL_STORAGE(){
        return ContextCompat.checkSelfPermission(activity, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED;
    }

    /**
     * 请求储存权限
     */
    public void WRPermissions(){
        if (notREAD_EXTERNAL_STORAGE()||notWRITE_EXTERNAL_STORAGE()) {
            String[] permissions = {Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.READ_EXTERNAL_STORAGE};
            activity.requestPermissions(permissions, REQUEST_CODE);
        }
    }
}



注意:必须在build.gradle中的defaultConfig添加targetSdkVersion 24(24是api版本,改成你自己的api版本)才能成功,我就是IDEA自动生成的没有这代码,所以sd卡上写入一直报错“权限被拒绝”
在这里插入图片描述
2023年10月16日:在群内大佬的指导下,上述方法的本质是对targetSdk进行降级,是不可取的

另外还要在权限清单里加上<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />权限(我自己只添加了这个权限读写都能成功)

  • 2
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值