自己写的剪切文件代码

这是一个Java程序,用于剪切(复制并删除源文件)一个非空文件夹及其内容。通过`pasteFile`方法递归遍历文件夹,使用`copyFile`方法复制文件并`deleteFile`方法删除源文件。程序中所有的IO操作都可能抛出异常。
摘要由CSDN通过智能技术生成
package com.itcast;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;

/*
 * 剪切一个非空文件夹
 */
public class Prac1 {
	public static void main(String[] args) throws IOException {
		File srcFile = new File("F:\\aa");
		File destFile = new File("E:\\aa");
		pasteFile(srcFile,destFile);
	}

	private static void pasteFile(File srcFile, File destFile) throws IOException {
		// TODO Auto-generated method stub

		File[] files = srcFile.listFiles();
		for (File file : files) {
			if (file.isFile()) {
				copyFile(file,destFile);
				deleteFile(file);
			}else{
				//递归,遍历文件夹
				pasteFile(new File(srcFile,file.getName()), new File(destFile,file.getName()));
			}
			srcFile.delete();
		}
		
	}
	
	private static void deleteFile(File srcFile) {
		// TODO Auto-generated method stub
		srcFile.delete();
	}

	//复制文件
	private static void copyFile(File srcFile, File destFile) throws IOException{
		//判断文件夹是否存在
		if (!destFile.exists()) {
			new File(destFile.getAbsolutePath()).mkdir();
		}
		//使用字节流读取文件
		BufferedInputStream bufferedInputStream = new BufferedInputStream(new FileInputStream(srcFile));
		File newFile = new File(destFile,srcFile.getName());
		//写入文件
		BufferedOutputStream bufferedOutputStream = new BufferedOutputStream(new FileOutputStream(newFile));
		
		//定义一个缓冲数组
		byte[] buf = new byte[1024];
		int len = 0;
		
		while ((len = bufferedInputStream.read(buf))!=-1) {
			bufferedOutputStream.write(buf, 0, len);
		}
		
		//关闭资源。
		bufferedOutputStream.close();
		bufferedInputStream.close();
		
	}
}
代码的所有IO异常都抛出去了,不是很好哈~
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值