android文件操作

android10 之前获取本地文件目录:

在android 10之前使用 Environment.getExternalStorageDirectory().getAbsolutePath()可获取sd卡中的文件存储目录,如果需要进行文件读取,需要在AndroidManifest.xml文件里面添加权限:


还需要获取动态权限:

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            
            if (checkSelfPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED ||
                    checkSelfPermission(Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
                ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.READ_EXTERNAL_STORAGE}, 1);
            } 
        } 

然后是创建文件夹及写入文件数据:

 String path = Environment.getExternalStorageDirectory().getAbsolutePath();
        File dirFile = new File(path);
        if (!dirFile.exists() || !dirFile.isDirectory()) {
            dirFile.mkdirs();
        }

        AssetManager assets = getAssets();
        try {
            File dataFile = new File(path, "mine.dat");
            if (!dataFile.exists() || dataFile.isDirectory()) {
                boolean file = dataFile.createNewFile();
                System.out.println("创建文件:" + file);
            }
            InputStream is = assets.open("bd_etts_text.dat");
            FileOutputStream fos = new FileOutputStream(dataFile);
            byte[] buffer = new byte[1024 * 1024];
            int count = 0;
            while ((count = is.read(buffer)) != -1) {
                fos.write(buffer, 0, count);
            }
            fos.flush();
            fos.close();
            is.close();
            System.out.println("文件下载到本地成功");
        } catch (IOException e) {
            System.out.println("文件下载出错!");
            e.printStackTrace();
        }

2、android 10创建文件

在AndroidManifest.xml中添加权限,并添加动态权限。Environment.getExternalStorageDirectory().getAbsolutePath()获取的文件路径是不能创建文件及文件夹,系统会报java.io.IOException: Permission denied异常,so创建文件需使用其他路径:

String path = getExternalFilesDir(null).getAbsolutePath() + "/cdd/app";
File dirFile = new File(path);
if (!dirFile.exists() || !dirFile.isDirectory()) {
   dirFile.mkdirs();
}
AssetManager assets = getAssets();
try {
   File dataFile = new File(path, "mine.dat");
   if (!dataFile.exists() || dataFile.isDirectory()) {
       boolean file = dataFile.createNewFile();
    }
    InputStream is = assets.open("bd_etts_text.dat");
    FileOutputStream fos = new FileOutputStream(dataFile);
    byte[] buffer = new byte[1024 * 1024];
    int count = 0;
    while ((count = is.read(buffer)) != -1) {
        fos.write(buffer, 0, count);
    }
    fos.flush();
    fos.close();
    is.close();
    System.out.println("文件下载到本地成功");
} catch (IOException e) {
    System.out.println("文件下载出错!");
    e.printStackTrace();
}

需要用getExternalFilesDir(null)方法来获取文件存储路径。

你可能感兴趣的:(Java)