2011-04-19 141 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

相關問題