Android11将文件拷贝到外部共享目录

1、上一篇文章已经讲述android11的分区问题,11已经不支持应用在根目录下进行读写了

        但是业务要求将日志 (.text)文件保存到外部斌进行分享,就需要将app自己目录下的文件转移          出来才能进分享。

2、核心代码(已经有老哥写过我整合易懂版)

/**
     *   将沙盒中的文件/data/data/包名/cache/test.txt 保存到外部存储区域 sdcard/test.txt
     */
    public static void handleWriteExternalStorage(Activity activity,String pathStr) {
        File sandFile = new File("/storage/emulated/0/Android/data/com.grpt.Nb/filesGrptNbDeviceLog/" + File.separator +  pathStr);
        Log.e("sandFile",sandFile.toString());
        if(!sandFile.exists()) {
            Toast.makeText(activity, "请先手动创建test.txt 并且保存到/data/data/包名/cache/下", Toast.LENGTH_LONG).show();
            return;
        }
        new Thread(new Runnable() {
            @Override
            public void run() {
                Uri externalUri = null;
                if(Build.VERSION.SDK_INT < Build.VERSION_CODES.Q) {
                    File externalFile = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS);
                    File destFile = new File(externalFile + File.separator + pathStr);
                    externalUri = Uri.fromFile(destFile);
                } else {
                    ContentResolver resolver = activity.getContentResolver();
                    ContentValues values = new ContentValues();
                    values.put(MediaStore.Downloads.DISPLAY_NAME, pathStr);
                    values.put(MediaStore.Downloads.RELATIVE_PATH, Environment.DIRECTORY_DOWNLOADS);//保存路径
                    Uri uri = MediaStore.Files.getContentUri("external");
                    externalUri = resolver.insert(uri, values);
                }

                boolean ret = copySandFileToExternalUri(activity, sandFile.getAbsolutePath(), externalUri);
                activity.runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        Toast.makeText(activity, "从沙盒" + sandFile.getAbsolutePath() + "中拷贝文件到外部存储"
                                + Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS).getAbsolutePath()
                                + ", 结果= " + ret, Toast.LENGTH_LONG).show();
                    }
                });
            }
        }).start();
    }

    /**
     * 拷贝沙盒中的文件到外部存储区域
     * @param filePath 沙盒文件路径
     * @param  externalUri 外部存储文件的 uri
     */
    public static boolean copySandFileToExternalUri(Context context, String filePath, Uri externalUri) {
        ContentResolver contentResolver = context.getContentResolver();
        InputStream inputStream = null;
        OutputStream outputStream = null;
        boolean ret = false;
        try {
            outputStream = contentResolver.openOutputStream(externalUri);
            File sandFile = new File(filePath);
            if(sandFile.exists()) {
                inputStream = new FileInputStream(sandFile);

                int readCount = 0;
                byte[] buffer = new byte[1024];
                while ((readCount = inputStream.read(buffer)) != -1) {
                    outputStream.write(buffer, 0 , readCount);
                    outputStream.flush();
                }
            }
            ret = true;
        } catch (Exception e) {
            Log.e("11", "copy SandFile To ExternalUri. e = " + e.toString());
            ret = false;
        } finally {
            try {
                if(outputStream != null) {
                    outputStream.close();
                }
                if(inputStream != null) {
                    inputStream.close();
                }
                Log.d("22", " input stream and output stream close successful.");
            } catch (Exception e) {
                e.printStackTrace();
                Log.e("33", " input stream and output stream close fail. e = " + e.toString());
            }
            return ret;
        }
    }

3、别忘了权限申请

public void onRequestPermissionsResult(int requestCode, @NonNull @NotNull String[] permissions, @NonNull @NotNull int[] grantResults) {
  
    ......
    } else if(requestCode == PERMISSION_CODE_WRITE_EXTERNAL) {
        if(grantResults[0] == PackageManager.PERMISSION_GRANTED) {
            handleWriteExternalStorage();
        }
    } 
     ......
}

整合老哥来自:我不勤奋v

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值