字節流實現文件和文件夾的拷貝

1. 文件的拷貝

public static void copyFile(File src, File dest) throws IOException {// 1.傳入的對象相當於建立聯繫
		// 2.選擇流
		InputStream input = new FileInputStream(src);
		OutputStream output = new FileOutputStream(dest);
		// 3.操作
		// 讀取文件內容
		byte[] data = new byte[1024];// 緩衝數組,數組長度大小可變
		int len = 0;// 實際接收長度
		while (-1 != (len = input.read(data))) {
			// 寫入數據
			output.write(data, 0, len);
			
		}
		output.flush();// 強制沖刷
		output.close();// 原則是先打開的後關閉
		input.close();
		
	}
方法的封裝:

public static void copyFile(String srcPath, String destPath) throws IOException {// 1.傳入的對象相當於建立聯繫
		
		copyFile(new File(srcPath), new File(destPath));// 匿名內部類
		
	}


2. 文件夾的拷貝

public static void copyDir(File src, File dest) throws IOException {
		
		if (src.getAbsolutePath().contains(dest.getAbsolutePath())) {
			
			System.out.println("父目錄不能複製到子目錄中");
			return;
			
		}
		if (src.isFile()) {// 如果是文件就直接拷貝 
			
			FileUtiles.copyFile(src, new File(dest, src.getName()));
			
		} else if (src.isDirectory()) {
			
			new File(dest, src.getName()).mkdirs();// 保證文件夾爲空時也能拷貝過去
			for (File temp : src.listFiles()) {

				copyDir(temp, new File(dest, src.getName()));

			}
		}
	}

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