标签:
需要引用笔记《文件拷贝的实现》的方法
1 public static void copyDirectory(File src,File dest){ 2 if(src.isDirectory()){ 3 dest=new File(dest,src.getName());//在dest文件夹下创建src文件夹 4 } 5 copyDir(src, dest); 6 } 7 public static void copyDir(File src,File dest){ 8 9 if(src.isDirectory()){ 10 dest.mkdirs(); 11 for(File sub:src.listFiles()){ 12 copyDirectory(sub, new File(dest,sub.getName())); 13 } 14 }else if(src.isFile()){ 15 copyFile(src, dest); 16 } 17 }
1 package com.IO; 2 import java.io.*; 3 public class CopyUtil { 4 /** 5 * 拷贝文件夹 6 * @param src 7 * @param dest 8 */ 9 public static void copyDirectory(String srcPath,String destPath){//重载copyDirectory()方法 10 File src=new File(srcPath); 11 File dest=new File(destPath); 12 copyDirectory(src, dest); 13 } 14 public static void copyDirectory(File src,File dest){ 15 if(src.isDirectory()){ 16 dest=new File(dest,src.getName());//在dest目录下创建一个src同名的文件 17 } 18 copyDir(src, dest); 19 } 20 public static void copyDir(File src,File dest){ 21 if(src.isDirectory()){ 22 dest.mkdirs(); 23 for(File file:src.listFiles()){ 24 copyDir(file, new File(dest,file.getName()));//重点!! 25 } 26 }else if(src.isFile()){ 27 copyFile(src, dest); 28 } 29 } 30 /** 31 * 拷贝文件 32 * @param src 33 * @param dest 34 */ 35 public static void copyFile(String srcPath,String destPath){ 36 File src=new File(srcPath); 37 File dest=new File(destPath); 38 copyFile(src, dest); 39 } 40 public static void copyFile(File src,File dest){ 41 BufferedInputStream bis=null; 42 BufferedOutputStream bos = null; 43 try { 44 bis = new BufferedInputStream(new FileInputStream(src)); 45 bos = new BufferedOutputStream(new FileOutputStream(dest)); 46 byte[] flush=new byte[1024]; 47 int len=0;//实际获取的数据长度 48 while(-1!=(len=bis.read(flush))){ 49 bos.write(flush);//写入数据 50 } 51 bos.flush(); 52 } catch (FileNotFoundException e) { 53 System.out.println("文件找不到"); 54 e.printStackTrace(); 55 } catch (IOException e) { 56 System.out.println("读取流失败"); 57 e.printStackTrace(); 58 }finally{ 59 60 try { 61 if(null!=bos){ 62 bos.close(); 63 } 64 if(null!=bis){ 65 bis.close(); 66 } 67 } catch (IOException e) { 68 System.out.println("关闭流失败!"); 69 e.printStackTrace(); 70 } 71 72 } 73 } 74 }
标签:
原文地址:http://www.cnblogs.com/JamKong/p/4447067.html