File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
The moose likes I/O and Streams and the fly likes Why read() method of FileInputStream returns int instead of byte? Big Moose Saloon
  Search | Java FAQ | Recent Topics
Register / Login
JavaRanch » Java Forums » Java » I/O and Streams
Reply Bookmark "Why read() method of FileInputStream returns int instead of byte?" Watch "Why read() method of FileInputStream returns int instead of byte?" New topic
Author

Why read() method of FileInputStream returns int instead of byte?

Suresh Rachuru
Greenhorn

Joined: Nov 26, 2011
Posts: 3
Hi All,

Oracle documentation (http://docs.oracle.com/javase/tutorial/essential/io/bytestreams.html) says "Using a int as a return type allows read() to use -1 to indicate that it has reached the end of the stream."

My doubt is why can't be return type is 'byte' as it can hold value -1 ? Any clarification is appreciated. Thanks
Matthew Brown
Bartender

Joined: Apr 06, 2010
Posts: 2686

The method needs to be able to read a byte of data (256 possible values) or indicate there are no more values. So it needs to return 257 possibilities. A byte can only hold 256. If it returned a byte, how do you tell the difference between reading a -1 from the file and reaching the end of the stream?
 
 
subject: Why read() method of FileInputStream returns int instead of byte?
 
Threads others viewed
RANDOMACCESSFILE
IO
What's wrong with the program?
byte to int??
Why does FileInputStream's read() method return integer?
developer file tools