2012-03-07 179 views
6

我正在使用Android。我的要求是我有一個目錄有一些文件,後來我下載了一些其他文件到另一個目錄,我的意圖是將最新目錄中的所有文件複製到第一個目錄中。在將文件從最新複製到第一個目錄之前,我需要從第一個目錄中刪除所有文件。如何將我的文件從一個目錄複製到另一個目錄?

+0

以及有時候看爲Android/Java文檔,或者至少使用「搜索」框可能是真真正有用的 – Blackbelt 2012-03-07 11:18:25

+0

你找到一個解決辦法?請指教? – marienke 2016-11-24 11:45:45

回答

21
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(); 
     } 
    } 

我不記得我在哪裏找到了這個,但它來自於我用來備份SQLite數據庫的有用文章。

+0

簡單而完美。不知道大文件能否正常工作,以防萬一,讓我們來測試它。 – jfcogato 2013-10-22 10:34:57

0

你也必須使用下面的代碼:

public static void copyDirectoryOneLocationToAnotherLocation(File sourceLocation, File targetLocation) 
     throws IOException { 

    if (sourceLocation.isDirectory()) { 
     if (!targetLocation.exists()) { 
      targetLocation.mkdir(); 
     } 

     String[] children = sourceLocation.list(); 
     for (int i = 0; i < sourceLocation.listFiles().length; i++) { 

      copyDirectoryOneLocationToAnotherLocation(new File(sourceLocation, children[i]), 
        new File(targetLocation, children[i])); 
     } 
    } else { 

     InputStream in = new FileInputStream(sourceLocation); 

     OutputStream out = new FileOutputStream(targetLocation); 

     // Copy the bits from instream to outstream 
     byte[] buf = new byte[1024]; 
     int len; 
     while ((len = in.read(buf)) > 0) { 
      out.write(buf, 0, len); 
     } 
     in.close(); 
     out.close(); 
    } 

} 
+0

將文件保存到本地成功 – 2016-11-03 07:53:36

+0

請嘗試在此處避免使用txtspk。快速搜索表明你用「u」表示「你」39次,「ur」表示「你的」25次。這是你爲志願者創造的大量修復工作。 – halfer 2017-08-07 00:03:38

5

阿帕奇fileutils中做到這一點很簡單,很好..

包括阿帕奇公地IO包添加公地io.jar

commons-io android gradle dependancy

compile 'commons-io:commons-io:2.4' 

添加該代碼

String sourcePath = Environment.getExternalStorageDirectory().getAbsolutePath() + "/TongueTwister/sourceFile.3gp"; 
     File source = new File(sourcePath); 

     String destinationPath = Environment.getExternalStorageDirectory().getAbsolutePath() + "/TongueTwister/destFile.3gp"; 
     File destination = new File(destinationPath); 
     try 
     { 
      FileUtils.copyFile(source, destination); 
     } 
     catch (IOException e) 
     { 
      e.printStackTrace(); 
     } 
相關問題