What value does read() return when it has reached the end of a file

The read() method returns -1 when it has reached the end of a file.

In Core Java, the read() method of the InputStream class returns an integer value. When it reaches the end of a file, it typically returns -1 to indicate the end of the stream.

Here’s a simple example:

java
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;

public class ReadFileExample {
public static void main(String[] args) {
try (InputStream inputStream = new FileInputStream("example.txt")) {
int data;
while ((data = inputStream.read()) != -1) {
// Process the data
System.out.print((char) data);
}
} catch (IOException e) {
e.printStackTrace();
}
}
}

In this example, the read() method is used in a loop to read each byte from the file until it reaches the end (-1). The loop then terminates, indicating that the end of the file has been reached.