Win a copy of Programmer's Guide to Java SE 8 Oracle Certified Associate (OCA) this week in the OCAJP forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

RandomAccessFile & FileInputStream read

 
Marlene Miller
Ranch Hand
Posts: 1392
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Are RandomAccessFile.read() and FileInputStream.read() related, when the input stream is created using the file descriptor from the random access file?

(I didn't find any clues in the source code.)
 
Jim Yingst
Wanderer
Sheriff
Posts: 18671
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Marlene! From testing it seems that the two are indeed related. Reading from the RAF seems to advance the file positoin read by the input stream, and vice versa. However I haven't seen any documentation about this. I would guess that this is undocumented behavior, and so it's probably a good idea to avoid code that uses multiple streams and RAFs referring to the same file simultaneously, unless you find explicit documentation somewhere.
In contrast, if you use a FileChannel obtained by the getChannel() method of RAF or a file input or output stream, you do get some explicit guarantees about its behavior relative to the RAF/stream, as well as relative to other FileChannels. There are still some annoying loopholes IMO in terms of shat's guaranteed here and what's not (see this lengthy discussion if you're curious) - but the situation is certainly better than that you originally described, for which there seem to be no guarantees. Unless I missed someting which is entirely possible. Hope that helps...
 
Marlene Miller
Ranch Hand
Posts: 1392
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thank you very much Jim (9990 posts, 10 more to go!).
Uh oh. Wrong forum again. Next time, IO and Streams.
>>avoid code that uses multiple streams and RAFs referring to the same file simultaneously
Yes, that was the reason for the question.
Thank you for the link. I will try to understand the whole thing.
 
Jim Yingst
Wanderer
Sheriff
Posts: 18671
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Uh oh. Wrong forum again. Next time, IO and Streams.
And hey, I didn't even have to say anything. Cool.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic