posted 17 years ago
Hm - the read() method certainly can return -1, but that's different from indicating that there's a -1 in the file. I believe that's the point of the question.
Ajay, how was the -1 stored in the file? Is it a text file? Or some kind of binary format?
If it's a text file, then assuming it uses a common ASCII-like encoding, -1 would be represented with two bytes: a 0x2D (a '-' character) followed by a 0x31 (a '1' character). If that's the sort of file you're dealing with, then I recommend using a Scanner to read the number. Or if you're using an older JDK than 1.5, use a BufferedReader to read a line from the file, and use parseInt() to convert the characters "-1" into a number. You may well need to do additional parsing if there is other data on the same line.
If it's not a text file, then you may want to use a DataInputStream for a variety of methods for converting bytes to primitives. You need to know if the number was written as one byte, two, four, etc.
If the number was written as a single byte in binary format, then you may also be able to convert it using something like this:
Here a "real" -1 would have been read as 255, because that's what binary 11111111 means when you assume a range of 0-255. Casting to byte forces it into the range -128 to 127, which converts 255 to -1.
So Ajay, these methods will all give you different answers. You really need to know how the data was written in the first place in order to parse it correctly. I hope at least one of these possibilities makes sense to you.
"I'm not back." - Bill Harding, Twister