Monday, April 25, 2011

Java read file as byte array

import java.io.*;

public class ByteFileReader {
    public static void main(String[] args) throws Exception {
 String fileName = "com/demo/io/test.txt";
 ByteFileReader r = new ByteFileReader();
 byte[] bytes = r.getBytesFromFile(new File(fileName));
 System.out.printf("Read %d bytes from file %s:\n", bytes.length, fileName);
 System.out.write(bytes, 0, bytes.length);
    }

    public byte[] getBytesFromFile(File file) throws IOException {
 if (! file.exists()) {
     return null;
 }

        // get the size of the file
        long length = file.length();
        if (length > Integer.MAX_VALUE) { 
    throw new IOException(
   String.format(
       "The file %s is too large to be hold in a byte array", 
       file.getName()
   )
       ); 
        }
    
 int len = (int) length;
 byte[] bytes = new byte[len];
    
        InputStream in = new FileInputStream(file);
    
        // read in the bytes
        int offset = 0, n = 0;
        while (offset < len && n >= 0) {
     n = in.read(bytes, offset, len - offset);
            offset += n;
        }
    
        if (offset < len) {
            throw new IOException("Faile to read all contents of file: " + file.getName());
        }
    
        in.close();
        return bytes;
    }
}

No comments:

Post a Comment

Chitika