代码之家  ›  专栏  ›  技术社区  ›  Anon

无法在Android中获取文件

  •  0
  • Anon  · 技术社区  · 7 年前

    这里是我之前写的代码

    在resultActivity中:

    File sdcard = Environment.getExternalStorageDirectory();
                        File file = new File(sdcard, data.getData().getPath());
                        ParseFileAggiornamentoAsyncTask asyncTaskLetturaFile = new ParseFileAggiornamentoAsyncTask(MainActivity.this,file);
                        asyncTaskLetturaFile.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
    

    file.exist() 它的返回总是错误的,所以我无法阅读它和其他东西。

    根据评论更新

    下面是触发startActivityForResult的代码

    if (checkSelfPermission(Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
                    requestPermissions(new String[]{Manifest.permission.READ_EXTERNAL_STORAGE},
                            MainConstant.MY_PERMISSIONS_REQUEST_READ_EXTERNAL_STORAGE);
                }else {
                    Intent fileintent = new Intent(Intent.ACTION_GET_CONTENT);
                    fileintent.setType("*/*");
                    fileintent.addCategory(Intent.CATEGORY_OPENABLE);
                    try {
                        startActivityForResult(Intent.createChooser(fileintent, "Select a File to Upload"), PICKFILE_RESULT_CODE);
                    } catch (ActivityNotFoundException e) {
                        Toast.makeText(MainActivity.this, MainActivity.this.getString(R.string.generic_error), Toast.LENGTH_LONG).show();
                        Log.e("tag", "No activity can handle picking a file. Showing alternatives.");
                    }
                    return true;
                }
    
    1 回复  |  直到 7 年前
        1
  •  0
  •   Jay    7 年前

    可能与清单关联,请参阅 https://developer.android.com/training/data-storage/files

    您可能需要在清单中包含以下行

    <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
    

    如果你已经有了这些,那么处理一个文件和在其他文章中是一样的。

    看见 How do I check if a file exists in Java?