1 5 package com.tc.util.io; 6 7 import java.io.File ; 8 import java.io.FileInputStream ; 9 import java.io.FileOutputStream ; 10 import java.io.IOException ; 11 import java.io.InputStream ; 12 import java.io.OutputStream ; 13 import java.util.Iterator ; 14 import java.util.LinkedList ; 15 import java.util.List ; 16 17 public class FileUtils { 18 19 22 public static void forceDelete(File directory, String extension) throws IOException { 23 Iterator files = org.apache.commons.io.FileUtils.iterateFiles(directory, new String [] { extension }, false); 24 while (files.hasNext()) { 25 File f = (File ) files.next(); 26 org.apache.commons.io.FileUtils.forceDelete(f); 27 } 28 } 29 30 33 public static void copyFile(File src, File dest) throws IOException { 34 List queue = new LinkedList (); 35 queue.add(new CopyTask(src.getCanonicalFile(), dest.getCanonicalFile())); 36 37 while (queue.size() > 0) { 38 CopyTask item = (CopyTask) queue.remove(0); 39 if (item.getSrc().isDirectory()) { 40 File destDir = item.getDest(); 41 destDir.mkdirs(); 42 43 if (!destDir.isDirectory()) { throw new IOException ("Destination directory does not exist: " + destDir); } 44 45 String [] list = item.getSrc().list(); 46 for (int i = 0; i < list.length; i++) { 47 File _src = new File (item.getSrc(), list[i]); 48 File _dest = new File (item.getDest(), list[i]); 49 queue.add(new CopyTask(_src, _dest)); 50 } 51 } else if (item.getSrc().isFile()) { 52 doCopy(item.getSrc(), item.getDest()); 53 } else { 54 throw new IOException (item.getSrc() + " is neither a file or a directory"); 55 } 56 } 57 58 } 59 60 private static void doCopy(File src, File dest) throws IOException { 61 FileInputStream in = null; 62 FileOutputStream out = null; 63 byte[] buffer = new byte[1024 * 8]; 64 int count; 65 try { 66 in = new FileInputStream (src); 67 out = new FileOutputStream (dest); 68 while ((count = in.read(buffer)) >= 0) { 69 out.write(buffer, 0, count); 70 } 71 } finally { 72 closeQuietly(in); 73 closeQuietly(out); 74 } 75 } 76 77 private static class CopyTask { 78 private final File src; 79 private final File dest; 80 81 public CopyTask(File src, File dest) { 82 this.src = src; 83 this.dest = dest; 84 } 85 86 public File getSrc() { 87 return src; 88 } 89 90 public File getDest() { 91 return dest; 92 } 93 } 94 95 public static void closeQuietly(InputStream is) { 96 if (is != null) { 97 try { 98 is.close(); 99 } catch (IOException ioe) { 100 } 102 } 103 } 104 105 public static void closeQuietly(OutputStream os) { 106 if (os != null) { 107 try { 108 os.close(); 109 } catch (IOException ioe) { 110 } 112 } 113 } 114 115 } 116 | Popular Tags |