java复制文件到指定目录_java-通过IO流复制文件夹到指定目录

这个Java程序展示了如何使用BufferedInputStream和BufferedOutputStream来复制文件,以及递归遍历并复制整个目录到目标位置。它首先创建目标目录,然后遍历源目录中的每个子文件和子目录,进行相应的复制操作。
摘要由CSDN通过智能技术生成

public classcopyDirectoryDemo {public static voidmain(String[] args) {

File srcFolder= new File("C:\\Users\\MA\\Desktop\\IOtest");

File destFolder= new File("C:\\Users\\MA\\Desktop\\IOtest\\test");

fun(srcFolder, destFolder);

}public static voidfun(File srcFolder, File destFolder) {

File[] fileArray=srcFolder.listFiles();if (!destFolder.exists()) {

destFolder.mkdir();

}for(File file : fileArray) {if(file.isDirectory()) {

String folderName=file.getName();

File newDestFolder= newFile(destFolder, folderName);

fun(file, newDestFolder);

}else{

String fileName=file.getName();

File destFile= newFile(destFolder, fileName);

copy(file, destFile);

}

}

}public static voidcopy(File file, File destFile) {

BufferedInputStream bis= null;

BufferedOutputStream bos= null;try{

bis= new BufferedInputStream(newFileInputStream(file));

bos= new BufferedOutputStream(newFileOutputStream(destFile));byte[] bys = new byte[1024];int len = 0;while((len=bis.read(bys))!=-1){

bos.write(bys,0,len);

}

}catch(FileNotFoundException e) {

e.printStackTrace();

}catch(IOException e){

e.printStackTrace();

}finally{if(bis!=null){try{

bis.close();

}catch(IOException e) {

e.printStackTrace();

}

}if(bos!=null){try{

bos.close();

}catch(IOException e) {

e.printStackTrace();

}

}

}

}

}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值