This week's book giveaway is in the iOS forum.
We're giving away four copies of Classic Computer Science Problems in Swift and have David Kopec on-line!
See this thread for details.
Win a copy of Classic Computer Science Problems in Swift this week in the iOS forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

RandomAccessFile giving wrong output  RSS feed

 
Ranch Hand
Posts: 534
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




 
Saloon Keeper
Posts: 8763
163
  • 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?
 
Saloon Keeper
Posts: 4115
48
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.
 
Rancher
Posts: 2973
32
  • 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?

 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!