IO流遞迴複製資料夾以及資料夾中的內容---師承劉意老師
阿新 • • 發佈:2019-02-08
package copyfloder;
/*
* 分析
* 1.建立目標資料夾
* 2.判斷原始檔夾是資料夾還是檔案
* a,是資料夾在目標資料夾建立新的資料夾在執行2
* b,是檔案直接將檔案複製到目標資料夾
*/
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
public class MuchCopy
{
public static void main(String[] args)throws IOException
{
//封裝源目錄
File srcFloder = new File("e:\\Android");
//封裝目標目錄
File destFloder = new File("e:\\java2");
//判斷目標檔案是否存在
if(!destFloder.exists()){
destFloder.mkdir();
}
fileOrFloder(srcFloder,destFloder);
}
private static void fileOrFloder(File srcFloder, File destFloder)throws IOException
{
// TODO Auto-generated method stub
//判斷原始檔是資料夾還是檔案
if(srcFloder.isDirectory()){
//建立資料夾的抽象目錄
File newDestFloder = new File(destFloder,srcFloder.getName());
//呼叫抽象目錄建立資料夾
newDestFloder.mkdir();
//獲取資料夾中的檔案或資料夾
File[] fileArray = srcFloder.listFiles();
//因為其為資料夾所以要判斷其內容的性質迴圈判斷
for(File file : fileArray){
fileOrFloder(file, newDestFloder);
}
}else{
//使用複製檔案的方法
//注意:srcflorder必須問為原始檔
// destFlorder必須為一個檔案一個目標的檔案
File newFile = new File(destFloder,srcFloder.getName());
copy(srcFloder,newFile);
}
}
private static void copy(File srcFloder, File destFloder)throws IOException
{
// TODO Auto-generated method stub
//位元組輸入流
BufferedInputStream bis = new BufferedInputStream(new FileInputStream(srcFloder));
//封裝位元組輸出流
BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(destFloder));
byte[] bys = new byte[1024];
int len =0;
while((len=bis.read(bys))!=-1){
bos.write(bys,0,len);
}
//釋放資源
bis.close();
bos.close();
}
}
理解:
存在遞迴的思想當其中含有資料夾時其操作和根目錄相同都是對資料夾複製,但有許多注意事項
資料夾建立理解:
File newfloder = new File(新資料夾目錄,資料夾名);
newfloder.mkdir;
指定檔案所存目錄和資料夾姓名,程式碼執行完後文件夾就建立完成了
注意:
1,建立新的資料夾後要及時變更新資料夾路徑
2,複製是另開一個新的資料夾,裡面的檔案資料夾的名字,及建立都得手動完成,並在使用前完成。
3,複製檔案是注意建立物件,注意檔名問題。
4,執行復制檔案函式引數的必須是檔案,兩個物件都得是檔案