public static byte[] transformToBytes(String aFilename) throws Exception { if(null==aFilename) { throw new NullPointerException("aFilename is null"); } File theFile = new File(aFilename); if(!theFile.isFile()) { throw new IllegalArgumentException("Path doesn't represent a file: " + aFilename); } if(!theFile.exists()) { throw new IllegalArgumentException("File not found: " + aFilename); } InputStream theIs = new BufferedInputStream(new FileInputStream(theFile)); ByteArrayOutputStream theRawData = new ByteArrayOutputStream(); byte theBuffer[] = new byte[1024]; int theBytesRead; try { while((theBytesRead=theIs.read(theBuffer)) != -1) { //System.out.println("read: " + theBytesRead + " bytes."); if( theBytesRead < 1024 ) { byte theSlice[] = new byte[theBytesRead]; System.arraycopy(theBuffer, 0, theSlice, 0, theBytesRead); theRawData.write(theSlice); } else { theRawData.write(theBuffer); } } } finally { theIs.close(); theRawData.close(); } return theRawData.toByteArray(); } |