public static byte [ ] readFile ( String fileName ) throws OSHelperException { File file = new File ( fileName ) ; if ( ! file . exists ( ) ) { throw new OSHelperException ( "File " + fileName + " does not exist" ) ; } if ( ! file . canRead ( ) ) { throw new OSHelperException ( "File " + fileName + " is not readable" ) ; } if ( ! file . isFile ( ) ) { throw new OSHelperException ( "File " + fileName + " is not a normal file" ) ; } RandomAccessFile raFile = null ; try { raFile = new RandomAccessFile ( fileName , "r" ) ; } catch ( FileNotFoundException ex ) { throw new OSHelperException ( "File " + fileName + " not found" ) ; } long fileLengthLong ; try { fileLengthLong = raFile . length ( ) ; } catch ( IOException ex ) { throw new OSHelperException ( ex ) ; } if ( fileLengthLong > Integer . MAX_VALUE ) { throw new OSHelperException ( "File length exceeds " + Integer . MAX_VALUE + " bytes: " + fileLengthLong ) ; } int fileLengthInt = ( int ) fileLengthLong ; byte [ ] bytes = new byte [ fileLengthInt ] ; try { raFile . read ( bytes ) ; } catch ( IOException ex ) { throw new OSHelperException ( ex ) ; } finally { try { raFile . close ( ) ; } catch ( IOException ex ) { throw new OSHelperException ( ex ) ; } } return bytes ; }
Read a file to a byte array