Win a copy of Kotlin in Action this week in the Kotlin forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

RandomAccessFile giving wrong output  RSS feed

 
Adam Chalkley
Ranch Hand
Posts: 512
4
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
hi guys,

I have not run into an error in quite a few days,but now I seem to have a problem,

my program seems to output the number 4 but the first number I wrote to the file was 5,when I try retrieve the first number it gives me 4,

here is the output
------4

I'm just wondering where the bug is in my code?

thanks




 
Stephan van Hulst
Saloon Keeper
Posts: 7802
142
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hard to say what exactly causes this, but it's likely a side-effect from the fact that you're not managing your resources properly. You should close a resource when you're done with it, and as soon as possible. The easiest way to do this is with a try-with-resources statement:

Alternatively, you can also just use one channel that's opened for reading and writing, and call position(0) on it when you want to start reading or writing from the beginning.

Why are you using channels instead of streams, by the way?
 
Carey Brown
Bartender
Posts: 2980
46
Eclipse IDE Firefox Browser Java MySQL Database VI Editor Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
read() returns the number of bytes read.

And PLEASE don't use a ".txt" file name suffix for binary data. Use ".dat" if you can't think of anything else.
 
Norm Radder
Ranch Foreman
Posts: 2240
28
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
That problem has been detailed in an earlier thread: https://coderanch.com/t/683078/java/ByteBuffer

What happened to the answer that was provided in that previous post?

 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!