JAVA 文件复制工具(new深度复制所有文件)

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

public class FileCopy {

	public static void testCopyFolder() {
		String sourceFilePath = "D:\\java_test";
		String targetFilePath = "D:\\alex-test";
		copyFile(sourceFilePath, targetFilePath);
//		int sourceFileNum = new File(sourceFilePath).listFiles().length;
//		int targetFileNum = new File(targetFilePath + "\\"+ new File(sourceFilePath).getName()).listFiles().length;
	}

	public static void testCopyFile() {
		String sourceFilePath = "D:\\test1.txt";
		String targetFilePath = "D:\\alex-test";
		copyFile(sourceFilePath, targetFilePath);
		System.out.println("Copy complete...");
	}

	/**
	 * 如需测试,请先把”第8题测试“文件夹中的文件复制到D盘根目录
	 */
	public static void main(String[] args) {
		File file = new File("D:\\test2.txt");
		if (!file.exists()) {
			try {
				file.createNewFile();
				System.out.println("file name is " + file.getName());
				file = file.getAbsoluteFile();
				System.out.println("absolute file is " + file);
				System.out.println("new File is created");
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		testCopyFolder();
		testCopyFile();
	}

	/**
	 * @param sourceFilePath
	 *            文件复制源
	 * @param targetFilePath
	 *            文件复制目标端
	 */
	public static void copyFile(String sourceFilePath, String targetFilePath) {
		File sourceFile = new File(sourceFilePath);
		File[] sourceFiles = null;
		if (sourceFile.isDirectory()) {
			targetFilePath += "\\" + sourceFile.getName();
			File targetFile = new File(targetFilePath);
			targetFile.mkdirs();
			sourceFiles = sourceFile.listFiles();
		} else if (sourceFile.isFile()) {
			sourceFiles = new File[] { sourceFile };
		}

		for (int i = 0; i < sourceFiles.length; i++) {
			if (sourceFiles[i].isDirectory()) {
				String newSourceFilePath = sourceFilePath + "\\"+ sourceFiles[i].getName();
				copyFile(newSourceFilePath, targetFilePath);
			} else {
				try {
					FileInputStream fis = new FileInputStream(sourceFiles[i]);
					FileOutputStream fos = new FileOutputStream(targetFilePath+ "\\" + sourceFiles[i].getName());
					int read = -1;
					while ((read = fis.read()) != -1) {
						fos.write(read);
					}
					fos.flush();
					fos.close();
					fis.close();
				} catch (FileNotFoundException e) {
					e.printStackTrace();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
	}
}

 

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值