android 开发时 Environment.getExternalStorageDirectory() 不可使用

在AndroidSDK29及以上版本中,不能使用Environment.getExternalStorageDirectory()。推荐使用getExternalCacheDir()结合File操作来创建文件路径,如Android/data/你的包名。此方法会在手机存储的特定应用目录下保存文件。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

注意Android SDK用29或者29上编译的时是无法使用 Environment.getExternalStorageDirectory()的,所以只能找个替代方式了

 String file_path = mContext.getExternalCacheDir() + File.separator ;
            new File(file_path).mkdirs();//会自动判断路径是否存在如果不存在,创建路径
            String dir = file_path + "文件名字";
            File file = new File(dir);
            if(!file.exists()){
                try{
                    file.createNewFile();
                }catch (IOException e){
                    Log.e("ALeeObj", e.toString());
                }
            }

有很多方法,但是注意保存的文件路径 有些就很迷了,上面方式保存的路径就在手机存储路径的Android - data -你自己的包名什么的了

package com.example.myapplication; import android.content.Context; import android.os.Build; import android.os.Environment; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.util.HashMap; import java.util.Map; public class FileSaveQQ { public static boolean saveUserInfo(Context context, String account, String password) { FileOutputStream fos = null; String state = Environment.getExternalStorageState(); if (state.equals(Environment.MEDIA_MOUNTED)) { String SDPath ; if (Build.VERSION.SDK_INT > 29) { SDPath = context.getExternalFilesDir(null).getAbsolutePath(); } else { SDPath = Environment.getExternalStorageDirectory().getPath(); } File file = new File(SDPath, "data.txt"); try { fos = new FileOutputStream(file); fos.write((account + ":" + password).getBytes()); //将数据转换为字节码的形式写入data.txt文件中 fos.close(); } catch (Exception e) { e.printStackTrace(); } } return true; } //从data.txt文件中获取存储的QQ账号和密码 public static Map<String, String> getUserInfo(Context context) { String content = ""; FileInputStream fis = null; String state = Environment.getExternalStorageState(); if (state.equals(Environment.MEDIA_MOUNTED)) { String SDPath ; if (Build.VERSION.SDK_INT > 29) { SDPath = context.getExternalFilesDir(null).getAbsolutePath(); } else { SDPath = Environment.getExternalStorageDirectory().getPath(); } File file = new File(SDPath, "data.txt"); try { fis = new FileInputStream(file); //获取文件的输入流对象fis byte[] buffer = new byte[fis.available()]; fis.read(buffer);//通过read()方法读取字节码中的数据
最新发布
03-24
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

ABClooklook

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值