1 package de.java2html.util; 2 3 import java.io.BufferedInputStream ; 4 import java.io.BufferedOutputStream ; 5 import java.io.ByteArrayOutputStream ; 6 import java.io.File ; 7 import java.io.FileInputStream ; 8 import java.io.FileOutputStream ; 9 import java.io.IOException ; 10 import java.io.InputStream ; 11 import java.io.OutputStream ; 12 import java.io.Reader ; 13 import java.io.Writer ; 14 15 18 public class IoUtilities { 19 private IoUtilities() { 20 } 22 23 public static byte[] readBytes(InputStream inputStream) throws IOException { 24 ByteArrayOutputStream byteOut = new ByteArrayOutputStream (); 25 copyStream(inputStream, byteOut); 26 return byteOut.toByteArray(); 27 } 28 29 public static void copyStream(InputStream in, OutputStream out) throws IOException { 30 byte[] buffer = new byte[4096]; 31 while (true) { 32 int bytesRead = in.read(buffer); 33 if (bytesRead == -1) { 34 break; 35 } 36 out.write(buffer, 0, bytesRead); 37 } 38 } 39 40 public static void close(OutputStream outputStream) { 41 if (outputStream != null) { 42 try { 43 outputStream.close(); 44 } 45 catch (IOException e) { 46 } 48 } 49 } 50 51 public static void close(InputStream inputStream) { 52 if (inputStream != null) { 53 try { 54 inputStream.close(); 55 } 56 catch (IOException e) { 57 } 59 } 60 } 61 62 public static void close(Writer writer) { 63 if (writer != null) { 64 try { 65 writer.close(); 66 } 67 catch (IOException e) { 68 } 70 } 71 } 72 73 public static void close(Reader reader) { 74 if (reader != null) { 75 try { 76 reader.close(); 77 } 78 catch (IOException e) { 79 } 81 } 82 } 83 84 public static void copy(File sourceFile, File destinationFile) throws IOException { 85 if (!ensureFoldersExist(destinationFile.getParentFile())) { 86 throw new IOException ("Unable to create necessary output directory " + destinationFile.getParentFile()); 88 } 89 BufferedInputStream bis = null; 90 BufferedOutputStream bos = null; 91 try { 92 bis = new BufferedInputStream (new FileInputStream (sourceFile)); 93 bos = new BufferedOutputStream (new FileOutputStream (destinationFile)); 94 copyStream(bis, bos); 95 } 96 finally { 97 close(bis); 98 close(bos); 99 } 100 } 101 102 public static boolean ensureFoldersExist(File folder) { 103 if (folder.exists()) { 104 return true; 105 } 106 return folder.mkdirs(); 107 } 108 109 public static File exchangeFileExtension(File file, String newFileExtension) { 110 String fileName = file.getAbsolutePath(); 111 int index = fileName.lastIndexOf('.'); 112 if (index == -1) { 113 throw new IllegalStateException ("Unable to determine file extension from file name '" + fileName 115 + "'"); } 117 return new File (fileName.substring(0, index + 1) + newFileExtension); 118 } 119 } | Popular Tags |