Friday, December 10, 2010

Reading a file into a Byte Array

To read a file (image file) into a Byte Array all we need to is copy the next function into your source code.

I tweaked it to fit my needs, however it is not entirely mine. I found it by goggling a while ago (don't remember when) and most of the credits will have to go to the creator (sorry... don't know who you are either, because the page where I found this function didn't have anything regarding the creator).


public byte[] readBytes(String pathToImage) {
 int read = 0;
 int numRead = 0;
 byte[] filebytes = null;

 try {
  File file = new File(pathToImage);

  if (file.exists()) {

   int size = (int) file.length();  //File length

   if (size > Integer.MAX_VALUE) {
    System.out.println("File too big !!!");
    return null;
   }

   filebytes = new byte[size];

   DataInputStream dis = new DataInputStream(new FileInputStream(file));

   while (read < filebytes.length
     && (numRead = dis.read(filebytes, read, filebytes.length - read)) >= 0) {
    read = read + numRead;
   }

   dis.close();

   if (read < filebytes.length) {
    System.out.println("Error reading file: " + file.getName());
   }

  }
  file = null;

 } catch (Exception e) {
  //Do something here
 }

 return filebytes;
}

Usage:
//Call function
byte[] imageFile = readBytes("c:\image.jpg");

Don't forget to include this:
import java.io.DataInputStream;
import java.io.File;
import java.io.FileInputStream;

and that's it.

So... what's missing ?

  • Give credits ... done
  • Function that reads image files into byte array ...done

Need help with something else? You know what to do ;)

Good luck.

No comments:

Post a Comment