2016-08-24 76 views
0

我使用意圖獲取圖片路徑並將其打開到文件中。我可以打開「Camera」文件夾中分配的文件,如「/storage/emulated/0/DCIM/Camera/IMG_20160817_232858.jpg」,但我無法在「/storage/emulated/0/Pictures/1634894_.png」等位置打開文件。 。使用file.exists()它只是說它沒有。 需要說我使用API​​ 23,並且我請求READ_EXTERNAL_STORAGE,所以這不應該成爲一個問題......但即使如此,我也無法訪問這些文件。 什麼可能是錯的?Android ENOENT與某些文件

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

     if (requestCode == RESULT_LOAD_IMG && resultCode == RESULT_OK && null != data) { 
      Uri selectedImage = data.getData(); 
      String[] filePathColumn = {MediaStore.Images.Media.DATA}; 

      Cursor cursor = getContentResolver().query(selectedImage, 
        filePathColumn, null, null, null); 
      cursor.moveToFirst(); 

      int columnIndex = cursor.getColumnIndex(filePathColumn[0]); 
      String picturePath = cursor.getString(columnIndex); 
      File file = new File(picturePath); 
      if(file.exists()) { 

      } else { 

      } 
      cursor.close(); 
     } 
    } 

更新:它不與來自同一個文件夾中的所有文件,恰巧只是其中的一部分,但他們真的存在,因爲我可以從庫中打開它們。

Update2: 我用這個意圖。

Intent galleryIntent = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI); 
     startActivityForResult(galleryIntent, RESULT_LOAD_IMG); 

UPDATE3: 運行時權限:

if (Build.VERSION.SDK_INT >= 23) { 
       if (checkSelfPermission(Manifest.permission.READ_EXTERNAL_STORAGE) 
         == PackageManager.PERMISSION_GRANTED) { 
        SomeWork(); 
       } else { 
        ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, 1); 
       } 
      } 
      else { 
       SomeWork(); 
      } 

權限在清單:

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

你在6.0上運行嗎? –

+0

是的,我用棉花糖 – PaulD

+0

你有運行時權限嗎? –

回答

1

MediaStore將索引圖像是無法從文件系統訪問你。沒有要求DATA列返回您可以使用的值。

相反,停止試圖讓File,並use the Uri itself

  • getContentResolver().openInputStream()得到它的InputStream
  • DocumentFile.fromSingleUri()獲得DocumentFile方便地訪問元數據(例如,MIME類型)
+0

仍然無法訪問相同的文件。 – PaulD

+0

這裏有:https://i.gyazo.com/0bf31c2030baf9f0a4e36ba71777c028.png但其他文件正常工作 – PaulD

+0

@PaulD:好的,現在這很奇怪。只需確認一下:你的代碼是直接由'onActivityResult()'觸發的(很像你問題中的代碼),使用'Intent'中的'Uri'?這不是從你的應用程序的過去運行中保存的'Uri',對吧?因爲如果是這樣的話,你的問題是[你訪問由'Uri'識別的內容的權限是非常有限的](https://commonsware.com/blog/2016/08/10/uri-access-一生,短高於你,可能-think.html)。 – CommonsWare