码迷,mamicode.com
首页 > 其他好文 > 详细

将一个目录里的所有目录和文件复制到另一个文件夹

时间:2016-06-16 23:13:30      阅读:216      评论:0      收藏:0      [点我收藏+]

标签:

package com.io.datain;

import java.io.*;

public class TestCopay1 {

	public static void main(String[] args) throws IOException {

		File file = new File("D:/Java/20160516-day1");

		File file1 = new File("D:/Java/20160516-day102");
		copyFileDir(file, file1);
	}

	/**
	 * 拷贝目录
	 * 
	 * @param file
	 * @param file1
	 */
	private static void copyFileDir(File file, File file1) {
		if (file.isDirectory()) {
			if (!file1.exists()) {
				file1.mkdirs();
			}

			File[] files = file.listFiles();
			for (File item : files) {
				if (item.isDirectory()) {
					copyFileDir(
							new File(file.getAbsolutePath(), item.getName()),
							new File(file1.getAbsolutePath(), item.getName()));
				} else {
					
					copyFile(new File(file.getAbsolutePath(), item.getName()),
							new File(file1.getAbsolutePath(), item.getName()));
				}
			}
		} else {
			copyFile(file, new File(file1.getAbsolutePath() + file.getName()));
		}
	}

	/**
	 * 拷贝文件
	 * 
	 * @param file
	 * @param file1
	 * @return
	 */
	private static boolean copyFile(File file, File file1) {

		// 创建读取文件的输入流,输出流
		// 输入流,对于程序来说,是向程序中输入数据,input
		FileInputStream fis = null;
		// 输出流,对于程序来说,是程序向程序外输出数据,output
		FileOutputStream fos = null;
		try {
			fis = new FileInputStream(file);
			fos = new FileOutputStream(file1);
			byte[] by = new byte[1024];
			int a = 0;
			a = fis.read(by);// 将读取到的数据放入字节数组by中,并获取放入到字节数组中的字节长度a
			while (a != -1) {
				/* 读取多个数据 */
				fos.write(by, 0, a);// 将数据写入b文件中
				a = fis.read(by);// 继续读取下一次
			}
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				fis.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
			try {
				fos.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return true;
	}
}

 

将一个目录里的所有目录和文件复制到另一个文件夹

标签:

原文地址:http://www.cnblogs.com/xunzhengzhi/p/5592212.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!