实现一个拷贝文件的工具类使用字符流还是字节流?

本文介绍了一个Java实现的文件和目录拷贝工具类,能够处理包括字符流和字节流在内的各种文件类型,特别适用于拷贝包含图片、声音等多媒体文件的目录。该工具通过递归方式实现目录及其下所有文件的复制,并避免了父目录拷贝到子目录中的错误。

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

拷贝的文件不确定是只包含字符流,有可能会包含字节流(如图片、声音、图像等),为考虑通用性要使用字节流。
以下为实现代码
package FileUtil;

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

public class FileUtil {
public static void copyDir(String srcPath,String desPath) throws IOException{
if(srcPath.equals(desPath)){
return;
}
File src=new File(srcPath);
File dest = new File(desPath);
copyDirAndFile(src,dest);
}
public static void copyDirAndFile(File src,File dest) throws IOException{
if(src.isFile()){
fileCopy(src, dest);
}else if(dest.getAbsolutePath().contains(src.getAbsolutePath())){
System.out.println(“父目录不能拷贝到子目录中”);
return;
}else{
if(!dest.exists()){
dest.mkdirs();
}
File[] fileList = src.listFiles();
for(File f:fileList){
if(f.isDirectory()){
copyDirAndFile(f,new File(dest,f.getName()));
}else{
fileCopy(f, new File(dest,f.getName()));
}
}
}
}
public static void fileCopy(File src,File dest) throws IOException{
if(src.isDirectory()||null==src){
System.out.println(“拷贝非文件,或文件为空”);
return;
}else if(dest.isDirectory()){
System.out.println(“拷贝文件,但目标路径为文件夹无法拷贝”);
return;
}
else{
InputStream is =new BufferedInputStream(new FileInputStream(src));
OutputStream os = new BufferedOutputStream(new FileOutputStream(dest,true));
byte[] car = new byte[1024];
int len=0;
while(-1!=(len=is.read(car))){
os.write(car, 0, len);
}
os.flush();
os.close();
is.close();
}
}
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值