Ricky Tran
Ricky Tran

Reputation: 145

why read () method returns -1 at EOF?

I am learning the java.io. In the read () method documentation, I saw the definition:

read () method returns the ASCII code of input bytes (0-255) and returns -1 at the end of file

Moreover, as I know, the ASCII code of EOF is 26.

So, why does the read() method return -1 instead of 26 for EOF. And, what does the return value -1 mean?

One more question: What is the null character (i.e. NUL), ASCII code: 0, used for? And if the file is blank (i.e. has no data), does the NUL character exist or not?

Upvotes: 0

Views: 1899

Answers (2)

Stephen C
Stephen C

Reputation: 718788

I saw the definition: "read () method returns the ASCII code of input bytes (0-255) and returns -1 at the end of file"

That definition is incorrect. The read() method does not return ASCII. It returns bytes, and places no interpretation on them. For a binary file, they are definitely not ASCII codes.

Here is the real definition of InputStream.read() ... as defined in the javadoc:

"public abstract int read() throws IOException

Reads the next byte of data from the input stream. The value byte is returned as an int in the range 0 to 255. If no byte is available because the end of the stream has been reached, the value -1 is returned."

Notice that there is no mention of ASCII.


Moreover, as I known, the ASCII code of EOF is 26.

Actually, there is no ASCII character that means EOF. Code 26 (CTRL-Z) is the ASCII SUB character. It is used in keyboard input to mean EOF on Windows, but not in other contexts. Indeed, on Mac OS and Linux ASCII code 4 (CTRL-D) serves that purpose.

At any rate, all unsigned byte values from 0 to 255 are valid data values that may appear in a file. There for it is necessary to use a different value to denote EOF.


One more question: the null character (NUL), ASCII code: 0, is used for what?

All sorts of things. Indeed, anything that the application chooses to use it for.

And if the file is blank (no data), the NUL character exists or not?

The NUL character does not represent an empty file, or the end of a file.

If a file has no data, then its length will be zero. The file length is part of the file's metadata, just like its filename, its owner and group, its permissions, its creation timestamp and so on.

Upvotes: 3

Elliott Frisch
Elliott Frisch

Reputation: 201439

The valid range of a byte value read from a file (on a "modern file" system) is 8-bits (that is, it is not necessarily ascii encoded, it might be binary). Since any value from 0 to 255 might be returned, it was necessary to indicate the end of file someway. You might prefer the classes and methods available from java.nio (generally) and the read methods available in Files (specifically) when dealing with small files.

Upvotes: 1

Related Questions