O'Reilly logo

Java™ Phrasebook by Timothy Fisher

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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 ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required