This post originated from an RSS feed registered with Java Buzz
by Goldy Lukka.
Original Post: Copying a File contents into a Byte Array
Feed Title: Xyling Java Blogs
Feed URL: http://www.javablogs.xyling.com/thisWeek.rss
Feed Description: Your one stop source for Java Related Resources.
Another very frequently asked question. How to convert a File to byteArray or how to get the contents of a file into a byte array? Well, after performing a long lasting search for that perfect code, I came across one from the javaalmanac (refer title of this post).
A snippet is pasted below:
// Create the byte array to hold the data byte[] bytes = new byte[(int) file.length]; //file is object of java.io.File for which you want the byte array
// Read in the bytes int offset = 0; int numRead = 0; while (offset < bytes.length && (numRead=is.read(bytes, offset, bytes.length-offset)) >= 0) { // is is the fileinputstream offset += numRead; }
Before I came across this snippet, here is what I had implemented based on my logic and java documentation.
// Create the byte array to hold the data byte[] bytes = new byte[(int) file.length]; //file is object of java.io.File for which you want the byte array
// Read in the bytes is.read(bytes); //is is the fileinputstream of file
I am wondering if there is anything wrong (or possibility of something happening wrong) in the code snippet I have written. Your comments?