JavaIO流基础笔记(二)

---------------------- ASP.Net+Android+IOS开发.Net培训、期待与您交流! ----------------------

最近在黑马论坛上看到一个发技术分的练习题,是关于IO文件操作的,正好学到这里,就自己尝试编写了下,题目是:将一个盘符里的文件夹复制到另一个盘符中(包含多层嵌套),代码如下:

package com.itheima;

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

public class CopyFile {

	private static final String ToDir = "D:";

	public static void main(String[] args) {
		try {
			CopyFile.copy("D:" + File.separator + "Workspaces", ToDir
					+ File.separator + "test");
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	private static boolean copy(String f1, String f2) throws IOException {
		// 源文件封装路径
		File in = new File(f1);
		// 目标文件封装路径
		File out = new File(f2);
		if (!in.exists()) {
			System.out.println("目标文件有误");
			return false;
		} else {
			System.out.println("源文件路径:" + in.getAbsolutePath());
			System.out.println("目标文件:" + out.getAbsolutePath());
		}
		//目标文件不存在就创建多级目录
		if (!out.exists())
			out.mkdirs();
		//获取当前文件中的所有文件和文件夹
		File[] files = in.listFiles();
		FileInputStream fin = null;
		FileOutputStream fou = null;
		for (File file : files) {
			if (file.isFile()) {
				try {
					fin = new FileInputStream(file);
					fou = new FileOutputStream(new File(f2 + File.separator
							+ file.getName()));
				} catch (FileNotFoundException e) {
					e.printStackTrace();
				}
				int c = 0;
				byte[] b = new byte[4096];
				while ((c = fin.read(b)) != -1) {
					fou.write(b, 0, c);
				}
				fin.close();
				fou.flush();
				fou.close();
			} else {
				//如果不是文件,接着利用递归思想调用自身,进入文件下一层
				copy(f1 + file.separator + file.getName(), f2 + file.separator
						+ file.getName());
			}
		}
		return false;
	}
}
其中我感觉,异常抛出的时机不是很合理,请大家给出评论,或者给出更好的代码。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值