java中利用IO流複製文件夾和文件

java中的IO流實現文件和文件夾的複製
package com.baojian.demo03;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

/*
 * 複製文件夾和文件/*
 * 參考https://www.cnblogs.com/qingfengzhuimeng/p/6776445.html
*/
public class TestCopyFloderAndFile {

	public static void main(String[] args) throws IOException {
		// 調用複製文件的方法, 傳遞文件源和文件複製的目的
		String sourcePath = "d:\\QQ";
		String destPath = "c:\\QQ";
		copyFile(sourcePath,destPath);
		System.out.println("**********文件夾複製完成**********");
		
	}
	// 複製文件夾的方法,利用了回調
	private static void copyFile(String sourcePath,String destPath) throws IOException{
		// 利用源文件路徑創建File對象
		File sourceFile = new File(sourcePath);
		// 判斷路徑是否合法
		if(!sourceFile.exists()){
			System.out.println("您輸入的文件源不是合法路徑!");
			return;
		}else if(sourceFile.isFile()){
			copyDocument(sourcePath,destPath);
			return;
		}
		// 利用目的路徑創建File對象
		File destFile = new File(destPath);
		// 判斷目的路徑是否存在,如果不存在則創建
		if(!destFile.exists()){
			destFile.mkdirs();
		}
		
		// 獲取目的源下面的所有文件和文件夾列表
		File[] files = sourceFile.listFiles();
		// 遍歷源文件下的文件類型如果是文件夾繼續調用copyFile方法,如果是文件調用文件複製方法
		for(File file : files){
			System.out.println(file.getName());
			// 如果是文件夾,繼續調用copyFile方法
			if(file.isDirectory()){
				copyFile(sourcePath + "\\" + file.getName(),destPath + "\\" + file.getName());
			}
			// 如果是文件,則調用文件的方法
			if(file.isFile()){
				copyDocument(sourcePath + "\\" + file.getName(),destPath + "\\" + file.getName());
				System.out.println("複製完成");
			}
		}
	
	}
	// 複製文件
	public static void copyDocument(String sourcePath,String destPath) throws IOException {
		// 創建字節緩衝流對象
		BufferedInputStream bis = new BufferedInputStream(new FileInputStream(sourcePath));
		BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(destPath));
		// 複製文件
		byte[] buf = new byte[1024];
		int len = 0;
		while((len = bis.read(buf))!=-1){
			bos.write(buf, 0, len);
		}
		bos.close();
		bis.close();
	}
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章