Home | Contact Us | FAQ | Search & Site Map | Link to Us
Sign In | Join | Other 45 Sites in Network
HomeAnnouncementsWhite Papers
Discussion GroupsFirst AidDatabasesJavaBeansGUIJava 3DVirtual MachineCORBASecurityToolsGeneral
Java DirectoryOpen Source ProjectsSample Book ChaptersUser GroupsWeb Resources
Related Topics
Databases.NETMore Topics ...

Java Forum / General / November 2006

Tip: Looking for answers? Try searching our database.

Write byte[] to file

Thread view: 
andrewzzz - 20 Nov 2006 13:04 GMT
hi guys,
what is the best way to write a byte array to a file?
thanks a lot,bye
Paul Davis - 20 Nov 2006 13:45 GMT
public void writeFile(byte[] data, String fileName) throws IOException{
    OutputStream out = new FileOutputStream(fileName);
    out.write(data);
    out.close();
}
> hi guys,
> what is the best way to write a byte array to a file?
> thanks a lot,bye
Thomas Hawtin - 20 Nov 2006 13:52 GMT
> public void writeFile(byte[] data, String fileName) throws IOException{
>     OutputStream out = new FileOutputStream(fileName);
    try {
>     out.write(data);
    } finally {
>     out.close();
    }
> }
>> hi guys,
>> what is the best way to write a byte array to a file?
>> thanks a lot,bye

Tom Hawtin
M.J. Dance - 20 Nov 2006 13:50 GMT
> hi guys,
> what is the best way to write a byte array to a file?

This question screams for a how-to-make-a-rat-pie recipe type of an answer. So,
without further ado...

1. First you have to obtain those bytes. The best way is to read them from a file:

File file = new File("afile");
InputStream in = new FileInputStream(file);
byte[] bytes = new byte[file.length()];
in.read(bytes);
in.close();

//Exception handling is left to a gentle reader.

2. Now write them to a file.

Simple, heh?

For other not-so-best ways you can also resort to

http://java.sun.com/docs/books/tutorial/essential/io/

or, if the going gets extremely tough,

http://www.justfuckinggoogleit.com/search?q=java+file+io+tutorial

Ta ta!
Thomas Hawtin - 20 Nov 2006 14:31 GMT
> InputStream in = new FileInputStream(file);
> byte[] bytes = new byte[file.length()];
> in.read(bytes);
> in.close();

Are you sure you don't want to check the return value of read, or use
another method from a decorator?

> or, if the going gets extremely tough,
>
> http://www.justfuckinggoogleit.com/search?q=java+file+io+tutorial

There's a lot of really bad advice on the web. Er, and on Usenet. Oh and
in books too.

Tom Hawtin
Chris Uppal - 20 Nov 2006 17:45 GMT
> byte[] bytes = new byte[file.length()];
> in.read(bytes);

/NEVER/ do that.  Never !

(There are other problems with the code too, but that one is unforgivable, even
for throwaway code).

   -- chris
Thomas Fritsch - 20 Nov 2006 18:30 GMT
>>byte[] bytes = new byte[file.length()];
>>in.read(bytes);
>
> /NEVER/ do that.  Never !

It should be replaced by something like this:

  byte[] bytes = new byte[file.length()];
  for (int n = 0, x; n < bytes.length; n += x ) {
    x = in.read(bytes, n, bytes.length - n);
    if (x < 0)
      throw new EOFException("stream shorter than expected");
  }

Signature

Thomas

Mark Rafn - 20 Nov 2006 19:43 GMT
>>>byte[] bytes = new byte[file.length()];
>>>in.read(bytes);

>> /NEVER/ do that.  Never !

>It should be replaced by something like this:
>
[quoted text clipped - 4 lines]
>       throw new EOFException("stream shorter than expected");
>   }

As long as you're checking for files that got shorter between creating your
byte array and actually reading, you might want to check that it got longer
with in.available() or just by reading another byte and seeing if one's there.

Alternately, you may prefer to just read whatever you can and not trust the
file.length() call at all.  This works even if you're not reading from a file
(like from getResourceAsStream() or a network stream).

 // best-guess starting size, make it up if we don't have a file.
 ByteArrayOutputStream baos = new ByteArrayOutputStream(file.length());
 byte[] buf = new byte[1024]; // read up to 1k at a time
 boolean done=false;
 while (!done) {
     int amtRead = in.read(buf);
     if (amtRead == -1) {
         done = true; // EOF
     } else {
         baos.write(buf, 0, amtRead);
     }
 }
 byte[] bytes = baos.toByteArray();
--
Mark Rafn    dagon@dagon.net    <http://www.dagon.net/>


Free Magazines

Get these publications absolutely FREE for up to 12 months. There are no hidden fees and no obligation. Simply choose a title, complete the application form and submit it. Read more ...

Oracle MagazineNetwork ComputingComputer WorldBio-IT WorldeWeekInformation WeekInfosecurity
 
Sign In
Join
My Latest Posts
My Monitored Threads
My Blog
My Photo Gallery
My Profile
My Homepage

Start New Thread
Enable EMail Alerts
Rate this Thread



©2008 Advenet LLC   Privacy Policy - Terms of Use
This website includes both content owned or controlled by Advenet as well as content owned or controlled by third parties.