Mohamed Amin
Mohamed Amin

Reputation: 1067

java read method returns -1 at the end of file

I am learning about java IO. In the read() method there is a notice that said

it returns -1 at the end of file

I don't know what this means? and what is the importance of -1 to be at the end of the file

example:

import java.io.*;  
class Simple{  
 public static void main(String args[])throws Exception{  
  FileReader fr=new FileReader("abc.txt");  
  int i;  
  while((i=fr.read())!=-1)  
  System.out.println((char)i);  

  fr.close();  
 }  
}  

Upvotes: 0

Views: 128

Answers (3)

Tharaka De Silva
Tharaka De Silva

Reputation: 61

-1 is when the end of the file has been reached.

Upvotes: 0

CollinD
CollinD

Reputation: 7573

Please check the docs first!

https://docs.oracle.com/javase/7/docs/api/java/io/InputStreamReader.html#read()

Relevant Section:

public int read() throws IOException Reads a single character.

Overrides: read in class Reader

Returns: The character read, or -1 if the end of the stream has been reached

Throws: IOException - If an I/O error occurs

For what it's worth, these are often referred to as sentinel values. Sentinel values are used to indicate some special condition via a return value that is an obvious invalid response (example: -1 since that is obviously not a character). Think of it like a status or error code. In this case, it means status: end of file.

Upvotes: 2

Nicolas Filotto
Nicolas Filotto

Reputation: 44965

-1 simply means that there is nothing more to read allowing to stop reading the stream before getting an IOException.

Upvotes: 1

Related Questions