java 如何从 Android 中的 URI 获取文件?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/42532956/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-03 06:42:27  来源:igfitidea点击:

How can I get File from URI in Android?

javaandroidfilepdfuri

提问by FaisalAhmed

I am trying to read a PDF file but it's throwing a NoSuchFileException. I have seen some solution for this but nothing seems to work in my case. I want to read the PDF file. Below is my code:

我正在尝试阅读 PDF 文件,但它抛出了一个NoSuchFileException. 我已经看到了一些解决方案,但在我的情况下似乎没有任何效果。我想阅读PDF文件。下面是我的代码:

 private void requestForResume() {
    Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
    intent.setType("*/*");
    intent.addCategory(Intent.CATEGORY_OPENABLE);
    Intent chooser = Intent.createChooser(intent, "Upload PDF File");
    startActivityForResult(chooser, REQUEST_CODE);
}

Here is how I am converting to file:

这是我转换为文件的方式:

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);

    if (requestCode == REQUEST_CODE) {
        Uri uri = data.getData();
        String fileName = uri.getLastPathSegment();

        File resumeFile=new File(uri.getPath());
        try {

            PDDocument pdfResume=PDDocument.load(resumeFile);
            PDFTextStripper stripper=new PDFTextStripper();
            String resumeText=stripper.getText(pdfResume);
            Log.d("location",resumeText);
        } catch (IOException e) {
            Log.d("location","unable to load pdf"+e.toString());
        }

        fileEditText.setText(fileName);        
    }
}

Please help me where I am wrong.

请帮助我我错的地方。

回答by Mohammad irshad sheikh

use this it return you path put just it on File

使用它返回你的路径把它放在文件上

@SuppressLint("NewApi")
public static String getFilePath(Context context, Uri uri) throws URISyntaxException {
    String selection = null;
    String[] selectionArgs = null;
    // Uri is different in versions after KITKAT (Android 4.4), we need to
    if (Build.VERSION.SDK_INT >= 19 && DocumentsContract.isDocumentUri(uri)) {//DocumentsContract.isDocumentUri(context.getApplicationContext(), uri))
        if (isExternalStorageDocument(uri)) {
            final String docId = DocumentsContract.getDocumentId(uri);
            final String[] split = docId.split(":");
            return Environment.getExternalStorageDirectory() + "/" + split[1];
        } else if (isDownloadsDocument(uri)) {
            final String id = DocumentsContract.getDocumentId(uri);
            uri = ContentUris.withAppendedId(
                    Uri.parse("content://downloads/public_downloads"), Long.valueOf(id));
        } else if (isMediaDocument(uri)) {
            final String docId = DocumentsContract.getDocumentId(uri);
            final String[] split = docId.split(":");
            final String type = split[0];
            if ("image".equals(type)) {
                uri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
            } else if ("video".equals(type)) {
                uri = MediaStore.Video.Media.EXTERNAL_CONTENT_URI;
            } else if ("audio".equals(type)) {
                uri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
            }
            selection = "_id=?";
            selectionArgs = new String[]{
                    split[1]
            };
        }
    }
    if ("content".equalsIgnoreCase(uri.getScheme())) {
        String[] projection = {
                MediaStore.Images.Media.DATA
        };
        Cursor cursor = null;
        try {
            cursor = context.getContentResolver()
                    .query(uri, projection, selection, selectionArgs, null);
            int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
            if (cursor.moveToFirst()) {
                return cursor.getString(column_index);
            }
        } catch (Exception e) {
        }
    } else if ("file".equalsIgnoreCase(uri.getScheme())) {
        return uri.getPath();
    }
    return null;
}

/**
 * @param uri The Uri to check.
 * @return Whether the Uri authority is ExternalStorageProvider.
 */
public static boolean isExternalStorageDocument(Uri uri) {
    return "com.android.externalstorage.documents".equals(uri.getAuthority());
}

/**
 * @param uri The Uri to check.
 * @return Whether the Uri authority is DownloadsProvider.
 */
public static boolean isDownloadsDocument(Uri uri) {
    return "com.android.providers.downloads.documents".equals(uri.getAuthority());
}

/**
 * @param uri The Uri to check.
 * @return Whether the Uri authority is MediaProvider.
 */
public static boolean isMediaDocument(Uri uri) {
    return "com.android.providers.media.documents".equals(uri.getAuthority());
}

File file =new File(getFilePath(getApplicationContext(),data.getData()));

File file =new File(getFilePath(getApplicationContext(),data.getData()));