The Artima Developer Community
Sponsored Link

Java Buzz Forum
Copying a File contents into a Byte Array

0 replies on 1 page.

Welcome Guest
  Sign In

Go back to the topic listing  Back to Topic List Click to reply to this topic  Reply to this Topic Click to search messages in this forum  Search Forum Click for a threaded view of the topic  Threaded View   
Previous Topic   Next Topic
Flat View: This topic has 0 replies on 1 page
Goldy Lukka

Posts: 1008
Nickname: xyling
Registered: Jan, 2004

Goldy Lukka is a Java Developer and an Entrepreneur. He is Founder of xyling.com.
Copying a File contents into a Byte Array Posted: Jun 14, 2005 8:16 AM
Reply to this message Reply

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.
Latest Java Buzz Posts
Latest Java Buzz Posts by Goldy Lukka
Latest Posts From Xyling Java Blogs

Advertisement
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?

[Resource-Type: Source Code; Category: Java/J2SE; XRating: 4.5]

Read: Copying a File contents into a Byte Array

Topic: Backpackit for highly effective people Previous Topic   Next Topic Topic: Eclipse BIRT 1.0 Released

Sponsored Links



Google
  Web Artima.com   

Copyright © 1996-2019 Artima, Inc. All Rights Reserved. - Privacy Policy - Terms of Use