Reading a File into a Byte Array

File file = new File(fileName);
											InputStream is = new FileInputStream(file);
											long length = file.length();
											byte[] bytes = new byte[(int)length];
											int offset = 0;
											int numRead = 0;
											while ((offset < bytes.length)
											&&
											((numRead=is.read(bytes,
											offset,
											bytes.length-offset))
											>= 0)) {
											offset += numRead;
											}
											is.close();

This phrase will read the file specified by fileName into the bytes byte array. Notice that the file.length() method returns us the length of the file in bytes as a long value, but we must use an int value to initialize the byte array, so we cast the long value to an int value. In a real program, you would probably want to be sure that the length value would indeed fit into an int type before blindly casting ...

Get Java™ Phrasebook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.