2016-07-18 92 views
2

我想要的圖像文件複製與此代碼:如何將圖像複製到SD卡上的現有目錄?

InputStream fileInputStream = null; 
OutputStream fileOutputStream = null; 
String inPath = "/storage/emulated/0/Pictures/MyImage.jpg"; 
String outPath = "/storage/extSdCard/MyFolder/MyImage.jpg"; 
    try { 
    verifyStoragePermissions(this); 
    fileInputStream = new FileInputStream(new File(inPath)); 
    File outputFile = new File(outPath); 
     if (!outputFile.exists()) { 
      try { 
       outPutFile.createNewFile(); 
      } catch (IOException e) { 
       e.printStackTrace(); 
      } 
     } 
    fileOutputStream = new FileOutputStream(outputFile); 

    byte[] buffer = new byte[1024]; 
    int read; 
    while ((read = fileInputStream.read(buffer)) != -1) { 
     fileOutputStream.write(buffer, 0, read); 
    } 
    fileInputStream.close(); 
    fileInputStream = null; 
    fileOutputStream.flush(); 
    fileOutputStream.close(); 
    fileOutputStream = null; 

    } catch (Exception e) { 
    Log.e("tag", e.getMessage()); 
    } 

而這是用於在SDK> = 23

// Storage Permissions 
private static final int REQUEST_EXTERNAL_STORAGE = 1; 
private static String[] PERMISSIONS_STORAGE = { 
     Manifest.permission.READ_EXTERNAL_STORAGE, 
     Manifest.permission.WRITE_EXTERNAL_STORAGE 
}; 

/** 
* Checks if the app has permission to write to device storage 
* 
* If the app does not has permission then the user will be prompted to grant permissions 
* 
* @param activity 
*/ 
public static void verifyStoragePermissions(Activity activity) { 
    // Check if we have write permission 
    int permission = ActivityCompat.checkSelfPermission(activity, Manifest.permission.WRITE_EXTERNAL_STORAGE); 

    if (permission != PackageManager.PERMISSION_GRANTED) { 
     // We don't have permission so prompt the user 
     ActivityCompat.requestPermissions(
       activity, 
       PERMISSIONS_STORAGE, 
       REQUEST_EXTERNAL_STORAGE 
     ); 
    } 
} 

而且結果驗證存儲權限的方法是這樣的錯誤發生在達到buffer行之前。

Unable to decode stream: java.io.FileNotFoundException: /storage/extSdCard/MyFolder/MyImage.jpg: open failed: ENOENT (No such file or directory) 

我有SD卡和畫廊的應用程序上MyFolder在我的設備將圖像複製到該目錄中沒有任何問題。

注意:權限是在清單中(在應用程序標記前的正確位置)和內部活動(對於skd> = 23)中授予的。

EDITS:

  1. 實現創建fileOutputStream之前文件的建議(沒有幫助)。

  2. 降低targetSdkVersion以超過與權限相關的任何可能的問題,但仍然沒有成功。

targetSdkVersion 22

  • 創建這樣File

    File outFile = new File("/storage/extSdCard", "MyFolder/MyImage.jpg");

    也取得了不結果。

  • 我測試它的Android版本22

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

    回答

    0

    這是我使用SAF來完成工作的方式。

    private void newcopyFile(File fileInput, String outputParentPath, 
            String mimeType, String newFileName) { 
    
    DocumentFile documentFileGoal = DocumentFile.fromTreeUri(this, treeUri); 
    
    String[] parts = outputParentPath.split("\\/"); 
    for (int i = 3; i < parts.length; i++) { //ex: parts:{"", "storage", "extSdCard", "MyFolder", "MyFolder", "MyFolder"} 
        if (documentFileGoal != null) { 
         documentFileGoal = documentFileGoal.findFile(parts[i]); 
        } 
    } 
    if (documentFileGoal == null) { 
        Toast.makeText(MainActivity.this, "Directory not found", Toast.LENGTH_SHORT).show(); 
        return; 
    } 
    
    DocumentFile documentFileNewFile = documentFileGoal.createFile(mimeType, newFileName); 
    
    InputStream inputStream = null; 
    OutputStream outputStream = null; 
    try { 
        outputStream = getContentResolver().openOutputStream(documentFileNewFile.getUri()); 
        inputStream = new FileInputStream(fileInput); 
    } catch (FileNotFoundException e) { 
        e.printStackTrace(); 
    } 
    try { 
        if (outputStream != null) { 
         byte[] buffer = new byte[1024]; 
         int read; 
         if (inputStream != null) { 
          while ((read = inputStream.read(buffer)) != -1) { 
           outputStream.write(buffer, 0, read); 
          } 
         } 
         if (inputStream != null) { 
          inputStream.close(); 
         } 
         inputStream = null; 
         outputStream.flush(); 
         outputStream.close(); 
         outputStream = null; 
        } 
    } catch (IOException e) { 
        e.printStackTrace(); 
    } 
    } 
    
    0

    您需要先創建文件,FileOutputStream會拋出異常,如果該文件不存在FileNotFoundException

    File outputFile = new File(outPath); 
    file.createNewFile(); 
    fileOutputStream = new FileOutputStream(outputFile); 
    
    +0

    '打開失敗:EACCES(權限被拒絕)' – Eftekhari

    +0

    試過你的答案,但沒有幫助。 – Eftekhari

    0

    如果您在您的應用gradle文件中使用targetSdkVersion 23(或更高版本),則需要明確請求權限(可以放入Activity的onCreate方法或a噸監聽方法),這樣的...

    private static final int CODE_WRITE_EXTERNAL = 10; 
        if (ContextCompat.checkSelfPermission(this,Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) { 
           if (ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.WRITE_EXTERNAL_STORAGE)) { 
            Log.d(TAG, "onCreate: " + "Show explanation"); 
            ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, CODE_WRITE_EXTERNAL); 
           } else { 
            ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, CODE_WRITE_EXTERNAL); 
           } 
          } else { 
           Log.d(TAG, "onCreate: " + "Permission already granted!"); 
           //Call your method to save the file 
          } 
    

    然後,你需要實現下一個回調方法

    @Override 
        public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) { 
         switch (requestCode) { 
          case CODE_WRITE_EXTERNAL : { 
           if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) { 
            Log.d(TAG, "onRequestPermissionsResult: Good to go!"); 
            //Call your mehotd here 
           } else { 
            Log.d(TAG, "onRequestPermissionsResult: Bad user"); 
           } 
          } 
         } 
        } 
    
    +0

    謝謝,但我已經實施讀寫權限請求sdk 23及以上,併爲簡單的問題決定不提及它。這是錯誤的決定抱歉。仍然有問題。 – Eftekhari