This week's book giveaway is in the OCMJEA forum.
We're giving away four copies of OCM Java EE 6 Enterprise Architect Exam Guide and have Paul Allen & Joseph Bambara on-line!
See this thread for details.
The moose likes Beginning Java and the fly likes What's wrong with the program? Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of OCM Java EE 6 Enterprise Architect Exam Guide this week in the OCMJEA forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "What Watch "What New topic
Author

What's wrong with the program?

Niyas Ahmed Sheikh
Ranch Hand

Joined: Jun 15, 2005
Posts: 129

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

Joined: Aug 16, 2005
Posts: 14117
    
  16

Take fis.read(bb) out of the loop.


Java Beginners FAQ - JavaRanch SCJP FAQ - The Java Tutorial - Java SE 7 API documentation
Scala Notes - My blog about Scala
Manuel Moons
Ranch Hand

Joined: Mar 05, 2002
Posts: 229
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

Joined: Aug 29, 2005
Posts: 74
Instead of reading character by character, consider using bufferedReader to read the whole line.

 
wood burning stoves
 
subject: What's wrong with the program?