Android私有储存文件和外部储存文件读写(适配6.0以上权限,不考虑SD卡)

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/u010218170/article/details/83244187

 Android中文件的使用(项目下载

  • raw、assets(项目内的文件)
  • getFilesDir()、getCacheDir()(app私有储存文件目录,app被卸载时文件被删除,不用考虑6.0及以上权限限制
  • Environment.getExternalStorageDirectory()(外部储存目录,其他应用可以访问,文件不会因为app被卸载而删除,适配6.0及以上机型

项目需要权限,AndroidManifest.xml设置

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

 读写文件代码

//读取文件中的字符串
public static String readFile(String filePath) {
    File file = new File(filePath);
    StringBuilder stringBuilder = new StringBuilder();
    char [] buf = new char[64];
    int count=0;
    try {
        FileInputStream fileInputStream = new FileInputStream(file);
        InputStreamReader reader = new InputStreamReader(fileInputStream, "UTF-8");
        while ((count = reader.read(buf)) != -1) {
            stringBuilder.append(buf,0,count);
        } 
    } catch (Exception e) {
        Log.e("读取文件出错",e.getMessage());
    }
    return stringBuilder.toString();
}

//将内容写入文件
public static void writeToFile(String filePath,String content){
    File file = getFile(filePath);
    try {
    FileWriter fw = new FileWriter(file,false);
    BufferedWriter bw = new BufferedWriter(fw);
    bw.write(content);
    bw.close();
    fw.close();
    } catch (Exception e) {
        Log.e("写文件出错",e.getMessage());
    }
}

//根据路径获取文件
public static File getFile(String filePath) {
    File dir = new File(filePath);
    if (!dir.getParentFile().exists()) {
        dir.getParentFile().mkdirs();
    }
    File file = new File(filePath);
    if (!file.exists()) {
        try {
            boolean flag = file.createNewFile();
            if (!flag) {
                Log.e("创建文件失败","createNewFile 失败");
            }
        } catch (Exception e) {
            Log.e("创建文件失败",e.getMessage());
        }
    }
    return file;
}

 私有存储文件读写(不用考虑6.0以上权限限制)

String file_path = getFilesDir().getPath() + File.separator + "self"+File.separator + "kk.txt";
FileUtils.writeToFile(file_path ,"内容");
String kk = FileUtils.readFile(file_path);
Log.e("kk",kk);

外部存储文件读写 (6.0以上权限限制)

  • 6.0权限适配
String file_path = Environment.getExternalStorageDirectory().getPath() + File.separator + "self"+File.separator + "tt.txt";
//检查版本是否大于M
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
    if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED || ContextCompat.checkSelfPermission(this, Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
        Log.e("权限检测","读或写文件权限未获取");
        ActivityCompat.requestPermissions(this, new String[] {Manifest.permission.WRITE_EXTERNAL_STORAGE,Manifest.permission.READ_EXTERNAL_STORAGE}, READ_WRITE_GRANT);
    } else {
        FileUtils.writeToFile(file_path,"内容");
        String tt = FileUtils.readFile(file_path );
        Log.e("tt",tt);
    }
} else {
    FileUtils.writeToFile(file_path,"内容");
    String tt = FileUtils.readFile(file_path);
    Log.e("tt",tt);
}
  •  权限申请结果处理
@Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
    super.onRequestPermissionsResult(requestCode, permissions, grantResults);
    boolean readGranted = true, writeGranted = true;
    for (int i = 0, j = permissions.length; i < j; i++) {
        if (grantResults[i] != PackageManager.PERMISSION_GRANTED) {
            if (Manifest.permission.WRITE_EXTERNAL_STORAGE.equals(permissions[i])) {
                writeGranted = false;
            } else if (Manifest.permission.READ_EXTERNAL_STORAGE.equals(permissions[i])) {
                readGranted = false;
            }
        }
    }
    //权限回调
    if (requestCode == READ_WRITE_GRANT) {
        if (writeGranted && readGranted) {
            FileUtils.writeToFile(file_path,content);
            String tt = FileUtils.readFile(file_path);
            Log.e("申请权限后 tt",tt);
        } else {
            Log.e("申请权限","读或写文件权限被拒绝");
        }
    }
}

遇到问题

 1、open failed: EISDIR (Is a directory)

//创建文件方式错误
//file.mkdirs();//创建目录
file.createNewFile()//创建文件

猜你喜欢

转载自blog.csdn.net/u010218170/article/details/83244187