androidQ(兼容) uri获取绝对路径和uri获取获取文件

//获取文件绝对路径

关于AndroidQ获取文件路径适配方案向下兼容
重要的事情说三遍
一定要有权限
一定要有权限
一定要有权限
这两个权限在AndroidQ上会默认转为AndroidQ所需要的权限,也可以用AndroidQ的新的权限(androidQ以下没有试过用androidQ的新权限)
  
  
  //(需要拍照时使用)
   






  //获取拍照和选取的图片的绝对路径
    public static String getFilePathFromURI(Context context, Uri contentUri) {
        File rootDataDir = context.getExternalFilesDir(null);
//        MyApplication.getMyContext().getExternalFilesDir(null).getPath();
        String fileName = getFileName(contentUri);
        if (!TextUtils.isEmpty(fileName)) {
            File copyFile = new File(rootDataDir + File.separator + fileName);
            copyFile(context, contentUri, copyFile);
            return copyFile.getAbsolutePath();
        }
        return null;
    }
    public static String getFileName(Uri uri) {
        if (uri == null) return null;
        String fileName = null;
        String path = uri.getPath();
        int cut = path.lastIndexOf('/');
        if (cut != -1) {
            fileName = path.substring(cut + 1);
        }
        return fileName;
    }

    public static void copyFile(Context context, Uri srcUri, File dstFile) {
        try {
            InputStream inputStream = context.getContentResolver().openInputStream(srcUri);
            if (inputStream == null) return;
            OutputStream outputStream = new FileOutputStream(dstFile);
            copyStream(inputStream, outputStream);
            inputStream.close();
            outputStream.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static int copyStream(InputStream input, OutputStream output) throws Exception, IOException {
        final int BUFFER_SIZE = 1024 * 2;
        byte[] buffer = new byte[BUFFER_SIZE];
        BufferedInputStream in = new BufferedInputStream(input, BUFFER_SIZE);
        BufferedOutputStream out = new BufferedOutputStream(output, BUFFER_SIZE);
        int count = 0, n = 0;
        try {
            while ((n = in.read(buffer, 0, BUFFER_SIZE)) != -1) {
                out.write(buffer, 0, n);
                count += n;
            }
            out.flush();
        } finally {
            try {
                out.close();
            } catch (IOException e) {
            }
            try {
                in.close();
            } catch (IOException e) {
            }
        }
        return count;
    }

 

//uri获取绝对路径

String path=getFilePathFromURI(context,uri);

//uri获取文件(使用上面的方法)

File file = new File(getFilePathFromURI(context,uri));



有更好的方法或者想法请提出意见,大家一起进步(下方github地址,内有文件)

https://github.com/beilvla/AndroidQ-/tree/master

你可能感兴趣的:(androidQ(兼容) uri获取绝对路径和uri获取获取文件)