• Post Reply Bookmark Topic Watch Topic
  • New Topic

What's wrong with the program?  RSS feed

 
Ranch Hand
Posts: 129
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

b.txt
-----
abcdefghij

output:
------
a
defghij

In the above pgm, the byte array bb[0] - bb[9] will have a - j.
But I got the above output. I thought the output should be: abcdefghij

What's wrong with the program?
 
Java Cowboy
Sheriff
Posts: 16083
88
Android IntelliJ IDE Java Scala Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Take fis.read(bb) out of the loop.
 
Ranch Hand
Posts: 229
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The read(byte[]) command will try to read 10 bytes at once (because your byte[] is 10 bytes). It will try to read those 10 bytes and when the inputstream is at it's end it will return -1. If less then 10 bytes can be read the read method will return the amount that can be read.

So if you follow these rules you can see why your output can be unpredictable.

You'd better do something like this:

 
Ranch Hand
Posts: 74
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Instead of reading character by character, consider using bufferedReader to read the whole line.

 
Put the moon back where you found it! We need it for tides and poetry and stuff. Like this tiny ad:
Rocket Oven Kickstarter - from the trailboss
https://coderanch.com/t/695773/Rocket-Oven-Kickstarter-trailboss
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!