【问题标题】:File not found when using file after selecting it Android选择文件后使用文件时找不到文件Android
【发布时间】:2016-02-16 10:21:06
【问题描述】:

类似于这个问题File not found error after selecting a file in android,我从 SD 中选择一个文件后得到一个文件未找到异常,但是提供的问题中的解决方案对我不起作用,但也导致另一个文件未找到异常。这是我的代码,它会在带有箭头的指示行准确地抛出一个 filenotfoundexception

private void fileChooser() {
    Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
    intent.setType("*/*");
    intent.addCategory(Intent.CATEGORY_OPENABLE);

    try {
        startActivityForResult(
                Intent.createChooser(intent, "Select a File to Upload"),0);
    } catch (android.content.ActivityNotFoundException ex) {
        // Potentially direct the user to the Market with a Dialog
        Toast.makeText(this, "Please install a File Manager.",
                Toast.LENGTH_SHORT).show();
    }
}

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    switch (requestCode) {
        case 0:
            if (resultCode == RESULT_OK) {
                // Get the Uri of the selected file
                Uri uri = data.getData();
                // Get the path
                try {
                    File f=new File(uri.getPath());
                    Bitmap mBitmap=null;
                    screenRuntime.getRewriteMachine().addSendFile(f);

                    ParcelFileDescriptor pfd=ParcelFileDescriptor.open(f,ParcelFileDescriptor.MODE_READ_ONLY); <-------------
                    PdfRenderer renderer=new PdfRenderer(pfd);
                    final int pageCount = renderer.getPageCount();

                    for (int i = 0; i < pageCount; i++) {
                        PdfRenderer.Page page = renderer.openPage(i);

                        // say we render for showing on the screen
                        page.render(mBitmap, null, null, PdfRenderer.Page.RENDER_MODE_FOR_DISPLAY);

                        // do stuff with the bitmap

                        // close the page
                        page.close();
                    }
                    RelativeLayout rl=(RelativeLayout)findViewById(R.id.mainContent);
                    rl.setBackground(new BitmapDrawable(content.getResources(),mBitmap));
                    // close the renderer
                    renderer.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
                Log.wtf("Sent file","Sent file");
                // Get the file instance
                // File file = new File(path);
                // Initiate the upload
            }
            break;
    }
    super.onActivityResult(requestCode, resultCode, data);
}

谁能告诉我为什么链接中的解决方案对我不起作用?或者我能做些什么来解决这个问题?或者可能出了什么问题? 这是日志的副本

第 110 行是 ParcelFileDescriptor pfd=ParcelFileDescriptor.open(f,ParcelFileDescriptor.MODE_READ_ONLY);

02-16 14:50:22.969  26284-26284/cmu.edu.screenshare W/System.err﹕          java.io.FileNotFoundException: No such file or directory
02-16 14:50:22.969  26284-26284/cmu.edu.screenshare W/System.err﹕ at android.os.Parcel.openFileDescriptor(Native Method)
02-16 14:50:22.969  26284-26284/cmu.edu.screenshare W/System.err﹕ at android.os.ParcelFileDescriptor.openInternal(ParcelFileDescriptor.java:253)
02-16 14:50:22.969  26284-26284/cmu.edu.screenshare W/System.err﹕ at android.os.ParcelFileDescriptor.open(ParcelFileDescriptor.java:199)
02-16 14:50:22.969  26284-26284/cmu.edu.screenshare W/System.err﹕ at cmu.edu.screenshare.MainActivity.onActivityResult(MainActivity.java:110)
02-16 14:50:22.969  26284-26284/cmu.edu.screenshare W/System.err﹕ at android.app.Activity.dispatchActivityResult(Activity.java:6160)
02-16 14:50:22.969  26284-26284/cmu.edu.screenshare W/System.err﹕ at android.app.ActivityThread.deliverResults(ActivityThread.java:3877)
02-16 14:50:22.969  26284-26284/cmu.edu.screenshare W/System.err﹕ at android.app.ActivityThread.handleSendResult(ActivityThread.java:3931)
02-16 14:50:22.969  26284-26284/cmu.edu.screenshare W/System.err﹕ at android.app.ActivityThread.access$1300(ActivityThread.java:144)
02-16 14:50:22.969  26284-26284/cmu.edu.screenshare W/System.err﹕ at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1408)
02-16 14:50:22.969  26284-26284/cmu.edu.screenshare W/System.err﹕ at android.os.Handler.dispatchMessage(Handler.java:102)
02-16 14:50:22.969  26284-26284/cmu.edu.screenshare W/System.err﹕ at android.os.Looper.loop(Looper.java:155)
02-16 14:50:22.969  26284-26284/cmu.edu.screenshare W/System.err﹕ at android.app.ActivityThread.main(ActivityThread.java:5696)
02-16 14:50:22.969  26284-26284/cmu.edu.screenshare W/System.err﹕ at java.lang.reflect.Method.invoke(Native Method)
02-16 14:50:22.969  26284-26284/cmu.edu.screenshare W/System.err﹕ at java.lang.reflect.Method.invoke(Method.java:372)
02-16 14:50:22.969  26284-26284/cmu.edu.screenshare W/System.err﹕ at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1029)
02-16 14:50:22.969  26284-26284/cmu.edu.screenshare W/System.err﹕ at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:824)

谢谢!

【问题讨论】:

  • @saeed 选择的文件不是图像,我使用 API 21 中的 pdfRenderer API 将页面从 pdf 文件呈现为位图。但这并不是真正的问题,也不是相关的,因为我的代码甚至没有到达那里。它在指示的行上崩溃。
  • @saeed ParcelFileDescriptor pfd=ParcelFileDescriptor.open(f,ParcelFileDescriptor.MODE_READ_ONLY);
  • 你能发布你的 logcat 吗?
  • @saeed 我也想过这个问题,但是我在我的一项测试中记录了 uri.getPath() 结果,它正确打印了文件的路径。
  • 你的检查设备sdk版本?

标签: android file


【解决方案1】:

使用下面的代码从选定的文件中获取路径

 public class SelectedFilePath{




            public static String getPath(final Context context, final Uri uri)
            {

                //check here to KITKAT or new version
                final boolean isKitKat = Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT;

                // DocumentProvider
                if (isKitKat && DocumentsContract.isDocumentUri(context, uri)) {

                    // ExternalStorageProvider
                    if (isExternalStorageDocument(uri)) {
                        final String docId = DocumentsContract.getDocumentId(uri);
                        final String[] split = docId.split(":");
                        final String type = split[0];

                        if ("primary".equalsIgnoreCase(type)) {
                            return Environment.getExternalStorageDirectory() + "/" + split[1];
                        }
                    }
                    // DownloadsProvider
                    else if (isDownloadsDocument(uri)) {

                        final String id = DocumentsContract.getDocumentId(uri);
                        final Uri contentUri = ContentUris.withAppendedId(
                                Uri.parse("content://<span id="IL_AD1" class="IL_AD">downloads</span>/public_downloads"), Long.valueOf(id));

                        return getDataColumn(context, contentUri, null, null);
                    }
                    // MediaProvider
                    else if (isMediaDocument(uri)) {
                        final String docId = DocumentsContract.getDocumentId(uri);
                        final String[] split = docId.split(":");
                        final String type = split[0];

                        Uri contentUri = null;
                        if ("image".equals(type)) {
                            contentUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
                        } else if ("video".equals(type)) {
                            contentUri = MediaStore.Video.Media.EXTERNAL_CONTENT_URI;
                        } else if ("audio".equals(type)) {
                            contentUri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
                        }

                        final String selection = "_id=?";
                        final String[] selectionArgs = new String[] {
                                split[1]
                        };

                        return getDataColumn(context, contentUri, selection, selectionArgs);
                    }
                }
                // MediaStore (and general)
                else if ("content".equalsIgnoreCase(uri.getScheme())) {

                    // Return the remote address
                    if (isGooglePhotosUri(uri))
                        return uri.getLastPathSegment();

                    return getDataColumn(context, uri, null, null);
                }
                // File
                else if ("file".equalsIgnoreCase(uri.getScheme())) {
                    return uri.getPath();
                }

                return null;
            }

            public static String getDataColumn(Context context, Uri uri, String selection,
                                               String[] selectionArgs) {

                Cursor cursor = null;
                final String column = "_data";
                final String[] projection = {
                        column
                };

                try {
                    cursor = context.getContentResolver().query(uri, projection, selection, selectionArgs,
                            null);
                    if (cursor != null && cursor.moveToFirst()) {
                        final int index = cursor.getColumnIndexOrThrow(column);
                        return cursor.getString(index);
                    }
                } finally {
                    if (cursor != null)
                        cursor.close();
                }
                return null;
            }

            public static boolean isExternalStorageDocument(Uri uri) {
                return "com.android.externalstorage.documents".equals(uri.getAuthority());
            }


            public static boolean isDownloadsDocument(Uri uri) {
                return "com.android.providers.downloads.documents".equals(uri.getAuthority());
            }


            public static boolean isMediaDocument(Uri uri) {
                return "com.android.providers.media.documents".equals(uri.getAuthority());
            }


            public static boolean isGooglePhotosUri(Uri uri) {
                return "com.google.android.apps.photos.content".equals(uri.getAuthority());
            }

    }

希望对你有帮助

【讨论】:

  • 让我知道你的结果
  • 很高兴为您提供帮助
  • 你的 URI.parse 是否应该像 class=\"IL_AD\"&gt; 的类跨度:Uri.parse("content://&lt;span id=\"IL_AD1\" class=\"IL_AD\"&gt;downloads&lt;/span&gt;/public_downloads"), Long.valueOf(id));
  • 如果文件来自 Google Drive 怎么办?
【解决方案2】:

您在此处收到的 URI 可能不是文件。它可能是一个内容 URI。

这种类型的 URI 必须从 getContentResolver().openInputStream(uri) 读取。

试试下面的代码:

        protected void onActivityResult(int requestCode, int resultCode, Intent data) {
                super.onActivityResult(requestCode, resultCode, data);
                addedFiles = new ArrayList<Attachment>();
                if (resultCode == RESULT_OK) {
                    switch (requestCode) {
                        case ADD_FILE_REQ_CODE:
                            if (data.getData() != null) {
                                Uri uri = data.getData();
                                File newFile = new File(uri.getPath());
                                try {

                                    InputStream ips = getContentResolver().openInputStream(uri);
                                    byte[] bytes = new byte[ips.available()];
                                    ips.read(bytes, 0, bytes.length);
                                    <<Your logic continues>>
}
}

【讨论】:

    猜你喜欢
    • 2015-07-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-10-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多