Win a copy of Murach's Python Programming this week in the Jython/Python forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

binary input and output?  RSS feed

 
Lee Xu
Ranch Hand
Posts: 77
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
hi,
how can I do binary input and output from/into file? Thank you very much.
Lee
 
Steve Deadsea
Ranch Hand
Posts: 125
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
FileInputStream and FileOutputStream.
They should be used as opposed to FileReader and FileWriter because they use straight bytes rather than bytes that get translated to characters.
 
Peter Chase
Ranch Hand
Posts: 1970
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
... or RandomAccessFile. That's the lowest-level API for file access.
From the responses I see here, few people seem to use RandomAccessFile, whereas I've found it quite useful. Would anyone like to suggest why one wouldn't want to use RandomAccessFile?
 
Jim Yingst
Wanderer
Sheriff
Posts: 18671
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
My experience is that RandomAccessFile is a lot slower than using FileOutputStream and FileInputStream. If the file can be processed linearly, RAF is a waste of time. Even for random access, I found that I could get better performance by creating a brand new FileOutputStream, using skip() to get to the desired position, reading from there, and then closing the reader.
Also, the readLine() method is basically useless if you need to support Unicode. I can create a BufferedReader wrapped around an InputStreamReader to read any encoding I want - not so with RAF. I mean, it's possible with RAF, but it's a lot more of a pain.
The fact that you can both read and write using the same class may seem like a benefit - but it generaly only works for wixed-length file formats. You can't replace a string with a longer string without overwriting subsequent data.
I'll concede RAF may be easier to use at first - but usually there's a better solution, for any given problem. IMO of course.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!