2011-04-19 98 views

回答

34

这个例子的改进版本:

// If targetLocation does not exist, it will be created. 
public void copyDirectory(File sourceLocation , File targetLocation) 
throws IOException { 

    if (sourceLocation.isDirectory()) { 
     if (!targetLocation.exists() && !targetLocation.mkdirs()) { 
      throw new IOException("Cannot create dir " + targetLocation.getAbsolutePath()); 
     } 

     String[] children = sourceLocation.list(); 
     for (int i=0; i<children.length; i++) { 
      copyDirectory(new File(sourceLocation, children[i]), 
        new File(targetLocation, children[i])); 
     } 
    } else { 

     // make sure the directory we plan to store the recording in exists 
     File directory = targetLocation.getParentFile(); 
     if (directory != null && !directory.exists() && !directory.mkdirs()) { 
      throw new IOException("Cannot create dir " + directory.getAbsolutePath()); 
     } 

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

有一些更好的错误处理,如果传递的目标文件之处在于不存在的目录更好把手。

15

查看示例here。 SD卡是外部存储器,因此您可以通过getExternalStorageDirectory访问它。

+0

是的..我知道可以使用getExternalStorageDirectory访问SD卡..但我怎样才能从一个文件夹复制到另一个相同SD卡的文件夹?谢谢 – 2011-04-19 11:19:20

+1

文件源=新文件(Environment.getExternalStorageDirectory(),“sourcedir”); File dest = new File(Environment.getExternalStorageDirectory(),“destDir”);然后使用链接中的代码。 – 2011-04-19 11:23:16

+0

。对不起...我无法理解,因为我是新来的...在链接他已经给一个文件复制到SD卡转换成字节流..但如何复制整个目录? – 2011-04-19 11:45:20

4

是的,这是可能的,即时通讯在我的代码中使用下面的方法。希望使用全给你: -

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

要移动的文件或目录,你可以使用File.renameTo(String path)功能

File oldFile = new File (oldFilePath); 
oldFile.renameTo(newFilePath); 
+3

这将从源目录中删除文件。 – Ankit 2013-11-14 11:27:51

相关问题