2015-06-23 59 views
0

嘗試使用下面的代碼到一個文件從一個目錄複製到另一個,並重新命名Android的複製和重命名從任何地方

String Path3= "/storage/extSDCard/DCIM/Camera/fred.jpg"; 
       File to = new  File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES), "Barr.jpg"); 
       File oldFile = new File (Path3); 
       oldFile.renameTo(to); 

它不會出現複製文件。在這種情況下,路徑Path3是在SD卡上,但我也需要它從設備上的一個目錄複製到另一個目錄

基本上我使用圖庫選擇器從某處將圖像從我轉換成uri一條路徑然後需要將文件從存儲位置複製到圖片目錄並重命名它

任何想法,我哪裏出錯了?

回答

0

我解決了它來自各種來源的錯誤方式。此產品的代碼工作:

File sourceLocation = new File (Path2); 
File targetLocation = new File (Path3 + "/" + imageFileName); 
       Log.v(TAG, "sourceLocation: " + sourceLocation); 
       Log.v(TAG, "targetLocation: " + targetLocation); 
       try { 
        int actionChoice = 2; 
        if(actionChoice==1){ 
         if(sourceLocation.renameTo(targetLocation)){ 
          Log.v(TAG, "Move file successful."); 
         }else{ 
          Log.v(TAG, "Move file failed."); 
         } 
        } 
        else{       
         if(sourceLocation.exists()){ 
          InputStream in = new FileInputStream(sourceLocation); 
          OutputStream out = new FileOutputStream(targetLocation); 
          byte[] buf = new byte[1024]; 
          int len; 
          while ((len = in.read(buf)) > 0) { 
           out.write(buf, 0, len); 
          } 
          in.close(); 
          out.close(); 
          Log.v(TAG, "Copy file successful."); 
         }else{ 
          Log.v(TAG, "Copy file failed. Source file missing."); 
         } 
        } 
       } catch (NullPointerException e) { 
        e.printStackTrace(); 
       } catch (Exception e) { 
        e.printStackTrace(); 
       }