读写文件工具类

public class Utils {
    private static String path1 = Environment.getExternalStorageDirectory().getAbsolutePath();
    private static String path2 = Environment.getDownloadCacheDirectory().getAbsolutePath();
    private static String pathExt = "/111/222/333/444/555/";
    private static String fileName = "6.txt";

    public static void write(String str) {
        String filePath = null;
        boolean hasSDCard =Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED);
        if (hasSDCard) {
            filePath = path1 + pathExt + fileName;
        } else {
            filePath = path2 + pathExt + fileName;
        }
        try {
            File file = new File(filePath);
            if (!file.exists()) {
                //mkdirs()方法生成多层文件夹
                //mkdir()方法生成一层层文件夹
//                File dir = new File(file.getParent());
//                dir.mkdirs();
                file.getParentFile().mkdirs();//生成文件外层的文件夹
                file.createNewFile();//生成文件
            }
            FileOutputStream os = new FileOutputStream(file);
            os.write(str.getBytes());
            os.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static String read() {
        String content = "";
        String filePath;

        boolean sdcard = Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED);
        if (sdcard) {
            filePath = path1 + pathExt + fileName;
        } else {
            filePath = path2 + pathExt + fileName;
        }
        try {
            File file = new File(filePath);
            if (file.exists()) {
                FileInputStream is = new FileInputStream(file);
                InputStreamReader inputReader = new InputStreamReader(is);//设置流读取方式
                BufferedReader buffReader = new BufferedReader(inputReader);
                String line;
                try {
                    while (null != (line = buffReader.readLine())) {
                        content += line + "\n";//读取的文件容
                    }
                    is.close();//关闭输入流
                } catch (IOException e) {
                    e.printStackTrace();
                } finally {
                    try {
                        if (null != is) {
                            is.close();
                        }
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        return content;
    }
}

1. 清单文件中添加读写权限

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />

2.Android6.0以上版本要动态申请读写权限

ArrayList<String> permissionList = new ArrayList<>();
private String[] permissions = {
		"android.permission.READ_EXTERNAL_STORAGE",
		"android.permission.WRITE_EXTERNAL_STORAGE" };
//检测是否有写的权限
//判断手机版本,如果低于6.0 则不用申请权限,直接拍照
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
	if (checkSelfPermission(permissions[0]) != PackageManager.PERMISSION_GRANTED) {
		permissionList.add(permissions[0]);
	}
	if (checkSelfPermission(permissions[1]) != PackageManager.PERMISSION_GRANTED) {
		permissionList.add(permissions[1]);
	}

	if (!permissionList.isEmpty()) {
		String[] permissions1 = permissionList.toArray(new String[permissionList.size()]);
		requestPermissions(permissions1, 1);
	} else {
		Utils.write("balabala");
		Utils.read();
	}
} else {
	Utils.write("balabala");
	Utils.read();
}


@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
	switch (requestCode){
		case 1:
			if (PackageManager.PERMISSION_GRANTED == grantResults[0]){
				Utils.write("balabala");
				Utils.read();
			} else {
				Log.d(TAG, "fail: ");
			}
			break;
	}
}

关于Android java.io.FileNotFoundException: open failed: EACCES (Permission denied)
在manifest application中加上 
android:requestLegacyExternalStorage="true"
Android Q 默认开启沙箱模式 导致出现文件读写失败
 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值