1 26 27 package net.sourceforge.cobertura.util; 28 29 import java.io.ByteArrayOutputStream ; 30 import java.io.File ; 31 import java.io.FileInputStream ; 32 import java.io.FileOutputStream ; 33 import java.io.IOException ; 34 import java.io.InputStream ; 35 import java.io.OutputStream ; 36 37 42 public abstract class IOUtil 43 { 44 45 53 public static void copyStream(InputStream in, OutputStream out) 54 throws IOException 55 { 56 if (in == null || out == null) 58 throw new NullPointerException (); 59 60 int el; 61 byte[] buffer = new byte[1 << 15]; 62 while ((el = in.read(buffer)) != -1) 63 { 64 out.write(buffer, 0, el); 65 } 66 } 67 68 74 public static byte[] createByteArrayFromInputStream(InputStream in) 75 throws IOException 76 { 77 ByteArrayOutputStream byteArray = new ByteArrayOutputStream (); 78 copyStream(in, byteArray); 79 return byteArray.toByteArray(); 80 } 81 82 88 public static void moveFile(File sourceFile, File destinationFile) 89 throws IOException 90 { 91 if (destinationFile.exists()) 92 { 93 destinationFile.delete(); 94 } 95 96 boolean succesfulMove = sourceFile.renameTo(destinationFile); 98 if (succesfulMove) 99 return; 100 101 InputStream in = null; 103 OutputStream out = null; 104 try 105 { 106 in = new FileInputStream (sourceFile); 107 out = new FileOutputStream (destinationFile); 108 copyStream(in, out); 109 } 110 finally 111 { 112 in = closeInputStream(in); 113 out = closeOutputStream(out); 114 } 115 116 sourceFile.delete(); 118 } 119 120 127 public static InputStream closeInputStream(InputStream in) 128 { 129 if (in != null) 130 { 131 try 132 { 133 in.close(); 134 in = null; 135 } 136 catch (IOException e) 137 { 138 System.err.println("Cobertura: Error closing input stream."); 139 e.printStackTrace(); 140 } 141 } 142 return in; 143 } 144 145 152 public static OutputStream closeOutputStream(OutputStream out) 153 { 154 if (out != null) 155 { 156 try 157 { 158 out.close(); 159 out = null; 160 } 161 catch (IOException e) 162 { 163 System.err.println("Cobertura: Error closing output stream."); 164 e.printStackTrace(); 165 } 166 } 167 return out; 168 } 169 170 } 171 | Popular Tags |