• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

What's wrong with the program?

 
Niyas Ahmed Sheikh
Ranch Hand
Posts: 129
  • 0
  • 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
Saloon Keeper
Pie
Posts: 15150
31
Android IntelliJ IDE Java Scala Spring
  • 0
  • 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
  • 0
  • 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
  • 0
  • 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.

 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic