java 将源目录下的文件拷贝到另一个目录下

本文介绍了一个实用的方法,用于将一个目录下的所有文件批量复制到另一个指定目录中。该方法通过Java实现,首先检查目标目录是否存在,若不存在则创建。接着验证源目录的有效性,并遍历源目录中的所有文件进行逐个复制。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >



<span style="white-space:pre">	</span>/***
	 *  将源目录下的文件拷贝到另一个目录下
	 * 
	 * @param originDirectory 源目录路径
	 * @param targetDirectory 目标目录路径
	 */
	public static void copyAllFile(String originDirectory,String targetDirectory) {
		// 源路径File实例
		File origindirectory = new File(originDirectory); 
		// 目标路径File实例
		File targetdirectory = new File(targetDirectory); 
		if (!targetdirectory.exists()) {
			// 目录不存在的情况下,创建目录。
			targetdirectory.mkdirs();
		}
		// 判断是不是正确的路径
		if (!origindirectory.isDirectory() || !targetdirectory.isDirectory()) { 
			log.error("不是正确的目录!");
			return;
		}
		// 源目录中的所有文件
		File[] fileList = origindirectory.listFiles();
		// 循环源目录中的文件拷贝到目标目录下
		for (File file : fileList) {
			// 判断是不是文件
			if (!file.isFile()) { 
				continue;
			}
			FileInputStream input = null;
			FileOutputStream output = null;
			try {
				input = new FileInputStream(file);
				output = new FileOutputStream(new File(targetdirectory,file.getName()));
				byte[] buf = new byte[1024000];
				int count = 0;
				while ((count = input.read(buf)) != -1) {
					output.write(buf, 0, count);
					output.flush();
				}
				output.flush();
			} catch (Exception e) {
				e.printStackTrace();
				log.error(e, e);
			} finally {
				if (null != input) {
					try {
						input.close();
					} catch (IOException e) {
						e.printStackTrace();
						log.error(e, e);
					}
				}
				if (null != output) {
					try {
						output.close();
					} catch (IOException e) {
						e.printStackTrace();
						log.error(e, e);
					}
				}
			}
		}
	}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值