java复制文件夹中的所有文件和文件夹到另一个文件夹中
生活随笔
收集整理的這篇文章主要介紹了
java复制文件夹中的所有文件和文件夹到另一个文件夹中
小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
package com.gblfy.ly.controller;import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;public class FileUtils {/*** 復(fù)制整個(gè)文件夾內(nèi)容* @param oldPath String 原文件路徑 如:c:/fqf* @param newPath String 復(fù)制后路徑 如: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("復(fù)制整個(gè)文件夾內(nèi)容操作出錯(cuò)");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("開始進(jìn)行圖片轉(zhuǎn)換:" + forStrTime + "毫秒");// copyFolder(oldPath, newPath) ;//1419毫秒copyDir(oldPath, newPath) ;//1099 毫秒forEndTime = System.currentTimeMillis();System.out.println("圖片轉(zhuǎn)換結(jié)束時(shí)間:" + forEndTime + "毫秒");long endToStart = (long) (forEndTime - forStrTime);System.out.println("圖片轉(zhuǎn)換消耗的時(shí)間:" + endToStart + "毫秒");}
}
總結(jié)
以上是生活随笔為你收集整理的java复制文件夹中的所有文件和文件夹到另一个文件夹中的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Ant Design Vue list表
- 下一篇: RabbitMQ控制台详解