IO流

流的分类

  • 按流向分
    • 输入流(Input)
    • 输出流(Output)
  • 按类型分
    • 字节流(InputStream/ OutputStream)
    • 字符流(Reader/ Writer)
  • 按功能分
    • 节点流(低级流:直接跟输入输出源对接)
      • FileInputStream/ FileOutputStream/ FileReader/ FileWriter/ PrintStream/ PrintWriter...
    • 处理流(高级流:建立在低级流的基础上)
      • 转换流(InputStream/ OutputStreamReader)
      • 缓冲流(BufferedInputStream/ BufferedOutputStream/ BufferedReader/ BufferedWriter

 目录复制实现

public class DirCopy {

	// 低级流实现单个文件复制
	public static void copyFile(File source, File desDir) throws IOException {
		
		File des = new File(desDir, source.getName());
		
		InputStream is = new FileInputStream(source);
		OutputStream os = new FileOutputStream(des);
		
		byte[] b = new byte[1024];
		int len = 0;
		while ((len = is.read(b)) != -1) {
			os.write(b, 0, len);
		}
		os.close();
		is.close();
	}

	// 整个目录的复制(实现关键是 递归)
	public static void copyDir(File sourceDir, File desDir) throws IOException {
		File copyFile = new File(desDir, sourceDir.getName());
		copyFile.mkdir();
		// 获得所有的文件对象(包括目录)
		File[] files = sourceDir.listFiles();
		// 遍历所有文件对象,若为标准文件,调用文件复制方法,否则对目录递归调用目录复制方法
		for (File file : files) {
			if (file.isFile()) {
				copyFile(file, copyFile);
			} else {
				File newDir = new File(desDir, file.getName());
				copyDir(file, newDir);
			}
		}

	}

	public static void main(String[] args) throws IOException {
		File sourceDir = new File("D:/test/test1");
		File desDir = new File("D:/test/test2");
		copyDir(sourceDir, desDir);
	}
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值