2011-05-17 42 views
0

我想要能夠移動或從Android設備的內部緩存中複製文件,並將其放入SD卡上的永久存儲。這是我到目前爲止有:從CacheDir複製文件(圖片)到SD卡

public void onClickSaveSecret(View v){ 

    File image = new File(getApplication().getCacheDir() + "/image.png"); 
    File newImage = new File(Environment.getExternalStorageDirectory() + "/image.png"); 

    Toast.makeText(this, "Image Saved", 100).show(); 

} 
+0

所以你有什麼問題?你不知道如何複製內容? – 2011-05-17 11:05:58

回答

7
/** 
* copy file from source to destination 
* 
* @param src source 
* @param dst destination 
* @throws java.io.IOException in case of any problems 
*/ 
void copyFile(File src, File dst) throws IOException { 
    FileChannel inChannel = new FileInputStream(src).getChannel(); 
    FileChannel outChannel = new FileOutputStream(dst).getChannel(); 
    try { 
     inChannel.transferTo(0, inChannel.size(), outChannel); 
    } finally { 
     if (inChannel != null) 
      inChannel.close(); 
     if (outChannel != null) 
      outChannel.close(); 
    } 
} 
+0

正是我需要的感謝。 – SamRowley 2011-05-17 13:32:40

0

試試這個方法

/** 
* @param sourceLocation like this /mnt/sdcard/XXXX/XXXXX/15838e85-066d-4738-a243-76c461cd8b01.jpg 
* @param destLocation /mnt/sdcard/XXXX/XXXXX/15838e85-066d-4738-a243-76c461cd8b01.jpg 
* @return true if successful copy file and false othrerwise 
* 
* set this permissions in your application WRITE_EXTERNAL_STORAGE ,READ_EXTERNAL_STORAGE 
* 
*/ 
public static boolean copyFile(String sourceLocation, String destLocation) { 
    try { 
     File sd = Environment.getExternalStorageDirectory(); 
     if(sd.canWrite()){ 
      File source=new File(sourceLocation); 
      File dest=new File(destLocation); 
      if(!dest.exists()){ 
       dest.createNewFile(); 
      } 
      if(source.exists()){ 
       InputStream src=new FileInputStream(source); 
       OutputStream dst=new FileOutputStream(dest); 
       // Copy the bits from instream to outstream 
       byte[] buf = new byte[1024]; 
       int len; 
       while ((len = src.read(buf)) > 0) { 
        dst.write(buf, 0, len); 
       } 
       src.close(); 
       dst.close(); 
      } 
     } 
     return true; 
    } catch (Exception ex) { 
     ex.printStackTrace(); 
     return false; 
    } 
} 

更多信息請訪問AndroidGuide

+2

1.如果您可以在問題中發佈相同的答案,則表示問題重複,因此您應該標記而不是回答問題。 2.請不要在您的答案中宣傳您的博客。 – ChrisF 2013-03-13 17:04:25