1 24 package org.riotfamily.common.io; 25 26 import java.io.File ; 27 import java.io.IOException ; 28 import java.io.InputStream ; 29 import java.io.OutputStream ; 30 import java.io.Reader ; 31 import java.io.Writer ; 32 33 import org.apache.commons.logging.Log; 34 import org.apache.commons.logging.LogFactory; 35 import org.springframework.util.FileCopyUtils; 36 37 public class IOUtils { 38 39 public static final int BUFFER_SIZE = 4096; 40 41 private static Log log = LogFactory.getLog(IOUtils.class); 42 43 public static int copy(InputStream in, OutputStream out) 44 throws IOException { 45 46 try { 47 int byteCount = 0; 48 byte[] buffer = new byte[BUFFER_SIZE]; 49 int bytesRead = -1; 50 while ((bytesRead = in.read(buffer)) != -1) { 51 out.write(buffer, 0, bytesRead); 52 byteCount += bytesRead; 53 } 54 out.flush(); 55 return byteCount; 56 } 57 finally { 58 closeStream(in); 59 } 60 } 61 62 public static int copy(Reader in, Writer out) 63 throws IOException { 64 65 try { 66 int byteCount = 0; 67 char[] buffer = new char[BUFFER_SIZE]; 68 int bytesRead = -1; 69 while ((bytesRead = in.read(buffer)) != -1) { 70 out.write(buffer, 0, bytesRead); 71 byteCount += bytesRead; 72 } 73 out.flush(); 74 return byteCount; 75 } 76 finally { 77 closeReader(in); 78 } 79 } 80 81 public static void closeStream(InputStream in) { 82 if (in != null) { 83 try { 84 in.close(); 85 } 86 catch (IOException ex) { 87 } 88 } 89 } 90 91 public static void closeStream(OutputStream out) { 92 if (out != null) { 93 try { 94 out.close(); 95 } 96 catch (IOException ex) { 97 } 98 } 99 } 100 101 public static void closeReader(Reader reader) { 102 if (reader != null) { 103 try { 104 reader.close(); 105 } 106 catch (IOException ex) { 107 } 108 } 109 } 110 111 public static void closeWriter(Writer writer) { 112 if (writer != null) { 113 try { 114 writer.close(); 115 } 116 catch (IOException ex) { 117 } 118 } 119 } 120 121 public static void move(File source, File dest) { 122 if (!source.renameTo(dest)) { 123 try { 124 log.info("Unable to move file " + source); 125 FileCopyUtils.copy(source, dest); 126 } 127 catch (IOException e) { 128 log.warn("Copy failed.", e); 129 } 130 delete(source); 131 } 132 } 133 134 public static void delete(File file) { 135 if (file != null && file.exists()) { 136 boolean deleted = file.delete(); 137 if (!deleted) { 138 file.deleteOnExit(); 139 } 140 } 141 } 142 } 143 | Popular Tags |