1 37 38 package net.sourceforge.cruisecontrol.util; 39 40 import java.io.File ; 41 import java.io.FileInputStream ; 42 import java.io.FileOutputStream ; 43 import java.io.IOException ; 44 import java.io.InputStream ; 45 import java.io.ObjectOutputStream ; 46 47 import org.apache.log4j.Logger; 48 49 public final class FileUtil { 50 51 private static final Logger LOG = Logger.getLogger(FileUtil.class); 52 53 private FileUtil() { 54 55 } 56 57 public static byte[] getFileAsBytes(File file) throws IOException { 58 InputStream is = new FileInputStream (file); 59 60 long length = file.length(); 62 63 if (length > Integer.MAX_VALUE) { 68 throw new IOException ("File too large. File size is " + length + ". Maximum allowed is " 70 + Integer.MAX_VALUE); 71 } 72 73 byte[] bytes = new byte[(int) length]; 75 76 int offset = 0; 78 int numRead = 0; 79 while (offset < bytes.length && (numRead = is.read(bytes, offset, bytes.length - offset)) >= 0) { 80 offset += numRead; 81 } 82 83 if (offset < bytes.length) { 85 throw new IOException ("Could not completely read file " + file.getName()); 86 } 87 88 is.close(); 90 return bytes; 91 } 92 93 public static String bytesToFile(byte[] data, String filePath) { 94 File outFile = new File (filePath); 95 try { 96 FileOutputStream fos = new FileOutputStream (outFile); 97 ObjectOutputStream oos = new ObjectOutputStream (fos); 98 oos.writeObject(data); 99 oos.close(); 100 fos.close(); 101 } catch (IOException e) { 102 String message = "Error creating output file"; 103 LOG.error(message, e); 104 System.err.println(message + " - " + e.getMessage()); 105 } 106 return filePath; 107 } 108 109 public static String bytesToFile(byte[] data, String parentDirName, String fileName) { 110 String filePath = null; 111 try { 112 filePath = new File (parentDirName, fileName).getCanonicalPath(); 113 } catch (IOException e) { 114 String message = "Could not determine canonical name for: " + parentDirName + File.separator + fileName; 115 System.err.println(message); 116 LOG.error(message, e); 117 } 118 return bytesToFile(data, filePath); 119 } 120 } 121 | Popular Tags |