Granny's Programming Pearls
"inside of every large program is a small program struggling to get out"
JavaRanch.com/granny.jsp
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

What's wrong with the program?  RSS feed

 
Niyas Ahmed Sheikh
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?
 
Jesper de Jong
Java Cowboy
Sheriff
Posts: 15865
81
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.
 
Manuel Moons
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:

 
Choon-Chern Lim
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.

 
Don't get me started about those stupid light bulbs.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!