java实现系统多级文件夹复制
生活随笔
收集整理的這篇文章主要介紹了
java实现系统多级文件夹复制
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
package com.jae;import java.io.*;//復制文件夾內的內容,包含多級文件夾
public class Test2 {public static void main(String[] args) throws Exception {//原文件夾地址File resPath = new File("E:\\Java\\分享");File destPath = new File("E:\\");//method(resPath, destPath);copy(resPath, destPath);}public static void copy(File src,File dest) throws Exception {File newDir = new File(dest,src.getName());newDir.mkdir();File[] subFiles = src.listFiles();for (File subFile : subFiles) {if(subFile.isFile()){BufferedInputStream bis = new BufferedInputStream(new FileInputStream(subFile));BufferedOutputStream bos =new BufferedOutputStream(new FileOutputStream(new File(newDir,subFile.getName())));int b;byte[] bytes = new byte[1024 * 8];while((b = bis.read(bytes)) != -1){bos.write(bytes,0,b);}bis.close();bos.close();}else{copy(subFile,newDir);//遞歸調用}}}public static void method(File dir, File destPath) throws IOException {//獲取源路徑的文件File[] files = dir.listFiles();//根目錄文件夾名String name1 = dir.getName();//遍歷源路徑的文件for (File file : files) {if (file.isFile()) {StringBuilder sb = new StringBuilder(destPath.getAbsolutePath());sb.append("\\").append(file.getName());//獲取盤符后面的路徑和文件名//String s = absolutePath.split(":")[1];//創建輸入流,封裝獲取到的文件的絕對路徑FileInputStream fis = new FileInputStream(file.getAbsolutePath());//目標路徑,定義目標路徑的盤符,和要復制的文件路徑和文件名//FileOutputStream fos = new FileOutputStream("F:" + s);FileOutputStream fos = new FileOutputStream(sb.toString());//復制文件操作int len;byte[] bytes = new byte[1024 * 8];while ((len = fis.read(bytes)) != -1) {fos.write(bytes, 0, len);fos.flush();}fos.close();fis.close();} else {StringBuilder sb = new StringBuilder(destPath.getAbsolutePath());sb.append("\\").append(name1).append("\\").append(file.getName());/*String name1 = file.getName();//獲取文件夾的路徑String name = file.getPath();//獲取盤符:后的文件夾路徑String s = name.split(":")[1];*///創建文件夾路徑//File file1 = new File("F:" + name1);File file1 = new File(sb.toString());file1.mkdirs();//System.out.println(name);method(file, file1);}}}
}
總結
以上是生活随笔為你收集整理的java实现系统多级文件夹复制的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: springCloud的注册中心Eure
- 下一篇: 四种保留小数后两位输出方法