2012-03-07 299 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(); 
     } 
相关问题