失眠网,内容丰富有趣,生活中的好帮手!
失眠网 > java复制文件夹中的所有文件和文件夹到另一个文件夹中

java复制文件夹中的所有文件和文件夹到另一个文件夹中

时间:2019-02-08 02:53:53

相关推荐

java复制文件夹中的所有文件和文件夹到另一个文件夹中

package com.gblfy.ly.controller;import java.io.File;import java.io.FileInputStream;import java.io.FileOutputStream;import java.io.IOException;public class FileUtils {/*** 复制整个文件夹内容* @param oldPath String 原文件路径 如:c:/fqf* @param newPath String 复制后路径 如:f:/fqf/ff* @return boolean*/public static void copyFolder(String oldPath, String newPath) {try {(new File(newPath)).mkdirs(); //如果文件夹不存在 则建立新文件夹File a=new File(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()){FileInputStream input = new FileInputStream(temp);FileOutputStream output = new FileOutputStream(newPath + "/" +(temp.getName()).toString());byte[] b = new byte[1024 * 5];int len;while ( (len = input.read(b)) != -1) {output.write(b, 0, len);}output.flush();output.close();input.close();}if(temp.isDirectory()){//如果是子文件夹copyFolder(oldPath+"/"+file[i],newPath+"/"+file[i]);}}}catch (Exception e) {System.out.println("复制整个文件夹内容操作出错");e.printStackTrace();}}public static void copyDir(String oldPath, String newPath) throws IOException {File file = new File(oldPath); //文件名称列表String[] filePath = file.list();if (!(new File(newPath)).exists()) {(new File(newPath)).mkdir();}for (int i = 0; i < filePath.length; i++) {if ((new File(oldPath + file.separator + filePath[i])).isDirectory()) {copyDir(oldPath + file.separator + filePath[i], newPath + file.separator + filePath[i]);}if (new File(oldPath + file.separator + filePath[i]).isFile()) {copyFile(oldPath + file.separator + filePath[i], newPath + file.separator + filePath[i]);}}}public static void copyFile(String oldPath, String newPath) throws IOException {File oldFile = new File(oldPath);File file = new File(newPath);FileInputStream in = new FileInputStream(oldFile);FileOutputStream out = new FileOutputStream(file);;byte[] buffer=new byte[2097152];while((in.read(buffer)) != -1){out.write(buffer);}}public static void main(String[] args) throws IOException {String oldPath="D:\\222\\data\\22";String newPath="D:\\222\\data\\55";long forStrTime = 0L;long forEndTime = 0L;forStrTime = System.currentTimeMillis();System.out.println("开始进行图片转换:" + forStrTime + "毫秒");// copyFolder(oldPath, newPath) ;//1419毫秒copyDir(oldPath, newPath) ;//1099 毫秒forEndTime = System.currentTimeMillis();System.out.println("图片转换结束时间:" + forEndTime + "毫秒");long endToStart = (long) (forEndTime - forStrTime);System.out.println("图片转换消耗的时间:" + endToStart + "毫秒");}}

如果觉得《java复制文件夹中的所有文件和文件夹到另一个文件夹中》对你有帮助,请点赞、收藏,并留下你的观点哦!

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。