Spartan Java

Read a file into a byte array

by on Jul.22, 2008, under Tips

Need to read a file into a byte array in memory, here’s a simple code sample.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
File file = new File("/somepath/myfile.ext");
FileInputStream is = new FileInputStream(file);
 
// Get the size of the file
long length = file.length();
 
if (length > Integer.MAX_VALUE) {
	throw new IOException("The file is too big");
}
 
// Create the byte array to hold the data
byte[] bytes = new byte[(int)length];
 
// Read in the bytes
int offset = 0;
int numRead = 0;
while (offset < bytes.length
	   && (numRead=is.read(bytes, offset, bytes.length-offset)) >= 0) {
	offset += numRead;
}
 
// Ensure all the bytes have been read in
if (offset < bytes.length) {
	throw new IOException("The file was not completely read: "+file.getName());
}
 
// Close the input stream, all file contents are in the bytes variable
is.close();
:, ,

7 Comments for this entry

  • Stronghead

    But this code cannot read the doc file which has table in it.. Any help??

  • ricardoz

    @stronghead: The code reads any file as binary content, so it really doesn’t mind what’s inside of it. You probably have a problem somewhere else, post your code if you want.

  • Shaun Hol

    Is there a bug here, or did I miss something ?
    The bytes buffer address isn’t getting updated during iteratons of the loop.

  • Shaun Hol

    Sorry ignore that – The second param is the offset into the array, not the offset into the file itself.

  • Jake

    What about the potential infinite loop if the stream encounters an EOF in the middle of the file and then numRead will continue to be set to 0 and hence will never increase the offset. and then we’ll cycle and cycle.

  • ricardoz

    @Jake: from the FileInputStream javadoc

    “Returns: the total number of bytes read into the buffer, or -1 if there is no more data because the end of the file has been reached.”

    The problem you mention shouldn’t happen since after EOF is found read should always return -1.

  • Paul

    The loop should be enclosed in a try/finally. ie:

    try { readloop } finally { is.close() } otherwise you will leave streams open if there is an error.

    Also, for efficiency, you would normally want to wrap your FileInputStream with a BufferedInputStream.
    use a

Leave a Reply

Looking for something?

Use the form below to search the site:

Still not finding what you're looking for? Drop a comment on a post or contact us so we can take care of it!

Visit our friends!

A few highly recommended friends...