Spartan Java

Read a file into a byte array

by ricardoz 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();

Bookmark it / share it:

  • Digg
  • del.icio.us
  • Google Bookmarks
  • Slashdot
  • Technorati
  • StumbleUpon
  • email
  • Facebook
  • LinkedIn
  • Print
  • NewsVine
  • Twitter
:, ,

2 Comments for this entry

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