To read a file into a bytearray in Java you can use the following snippet.

Sample Java

public static byte[] ReadFileIntoByteArray(File fileName) throws IOException {
    InputStream inputStream = new FileInputStream(fileName);
    byte[] bytes;
        
    try {
        long fileLength = fileName.length();
        if (fileLength > Integer.MAX_VALUE) {
            bytes = new byte[(int)fileLength];
			int readOffset = 0;
			int readCount = 0;
			while ((readCount=inputStream.read(bytes, readOffset, bytes.length-readOffset)) >= 0 && readOffset < bytes.length ) {
				readOffset += readCount;
			}
			if (bytes.length > readOffset) {
				throw new IOException("Could not completely read file " + fileName.getName());
			}
        }
		else{
			throw new IOException("File " + fileName.getName() + " too large (>2GB)!");
		}
    }
    finally {
        inputStream.close();
    }
    return bytes;
}

One thought on “How to read a file into a bytearray in Java”

Leave a Reply