`
hyxw5890
  • 浏览: 35295 次
  • 性别: Icon_minigender_1
  • 来自: 南京
社区版块
存档分类
最新评论

java实现文件夹下所有文件的拷贝

阅读更多
无聊写了一个实现文件-文件,文件夹-文件夹(包括源文件夹所有文件),文件-文件夹的拷贝的实用类.


import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.Reader;
import java.io.Writer;

public class Util {
	public static int buffer_size = 2048;

	private static void doCopy(File src, File dst) {
		if (src.isFile()) {
			try {
				copyFile(src, dst);

			} catch (IOException e) {
				e.printStackTrace();
			}
		} else {
			File dir = copyDirectory(src, dst);
			File[] files = src.listFiles();
			if (files.length == 0) {

			} else {
				for (File file : files) {
					doCopy(file, dir);
				}
			}
		}
	}

	public static void copy(File src, File dst) throws IOException {
		if (!src.exists() || !dst.exists())
			throw new FileNotFoundException();
		else if (src.isFile() && dst.isFile())
			copy(new FileReader(src), new FileWriter(dst));
		else if (src.isDirectory() && (!dst.isDirectory()))
			throw new IllegalArgumentException("Destination should be a directory!");
		else {
			doCopy(src, dst);
		}
		
	}

	private static void copyFile(File src, File dst) throws IOException {
		File file = new File(dst, src.getName());
		copy(new FileReader(src), new FileWriter(file));
	}

	private static File copyDirectory(File src, File dst) {
		File file = new File(dst, src.getName());
		file.mkdir();
		return file;
	}

	private static int copy(Reader in, Writer out) throws IOException {
		int byteCount = 0;
		try {
			int bytesReader = -1;
			char[] buffer = new char[buffer_size];

			while ((bytesReader = in.read(buffer)) != -1) {
				out.write(buffer, 0, bytesReader);
				byteCount += bytesReader;
			}
			out.flush();
		} finally {
			in.close();
			out.close();
		}
		return byteCount;
	}

}

1
0
分享到:
评论
4 楼 kjj 2009-02-04  
楼上比较精辟
3 楼 hyxw5890 2009-01-25  
sniciq 写道

为什么不用nio,里面有管道操作!

我是太无聊才写的,我错了。。
2 楼 sniciq 2009-01-25  
为什么不用nio,里面有管道操作!
1 楼 liujunsong 2009-01-25  
建议你可以调用一下 DOS命令:
xcopy XXXX XXXX /S/Y

相关推荐

Global site tag (gtag.js) - Google Analytics