java将图片写入一个文件夹_java 把一个文件夹里图片复制到另一个文件夹里

该Java代码示例展示了如何将一个文件夹中的所有图片复制到另一个文件夹中。通过创建`SendServer`类,使用`copyFolder`方法实现递归复制,并跟踪复制的文件数量。程序首先获取当前年月作为目标目录名,然后遍历源目录中的所有文件和子文件夹,逐个复制到新路径下。
摘要由CSDN通过智能技术生成

import java.io.File;

import java.io.FileInputStream;

import java.io.FileOutputStream;

import java.util.Calendar;public classSendServer {private int num = 0;public voidprocess() {

Calendar calendar=Calendar.getInstance();

String dir= calendar.get(Calendar.YEAR) + "" + getTimeString(calendar.get(Calendar.MONTH) + "");

String oldPath= "/img2" +dir;

String newPath= "/img5" +dir;try{

while(true){

System.out.println("复制" + oldPath + "目录开始");long t1 =System.currentTimeMillis();

num= 0;

copyFolder(oldPath, newPath);long t2 =System.currentTimeMillis();

System.out.println("复制目录结束,用时:" + (t2-t1) + "ms,共复制:" + num + "文件");

}

}catch(Exception ex) {

ex.printStackTrace();

}

}public voidcopyFolder(String oldPath, String newPath) {try{

File mFile= newFile(newPath);if(!mFile .exists()){

(new File(newPath)).mkdirs(); //如果文件夹不存在 则建立新文件夹

}

File a= newFile(oldPath);

String[] file=a.list();

File temp= null;for (int i = 0; i < file.length; i++) {if(oldPath.endsWith(File.separator)) {

temp= new File(oldPath +file[i]);

}else{

temp= new File(oldPath + File.separator +file[i]);

}if(temp.isFile()) {

String fileName= newPath + "/" +(temp.getName()).toString();

File testFile= newFile(fileName);if (!testFile.exists()) {

FileInputStream input= newFileInputStream(temp);

FileOutputStream output= newFileOutputStream(fileName);byte[] b = new byte[1024 * 5];intlen;while ((len = input.read(b)) != -1) {

output.write(b,0, len);

}

output.flush();

output.close();

input.close();

num++;

}

}if (temp.isDirectory()) {//如果是子文件夹

copyFolder(oldPath + "/" + file[i], newPath + "/" +file[i]);

}

}

}catch(Exception e) {

System.out.println("复制整个文件夹内容操作出错");

e.printStackTrace();

}

}privateString getTimeString(String time){if(time.length()<2){return "0" +time;

}else{returntime;

}

}

}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值