
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
What Value Does read() Method Return at End of File in Java
The read() method of the input stream classes reads the contents of the given file byte by byte and returns the ASCII value of the read byte in integer form. While reading the file if it reaches the end of the file this method returns -1.
Example
Assume we have a text file (sample.txt) in the current directory with a simple text saying “Hello welcome”. Following Java program reads the contents of the file byte by byte using the read() method and prints the integer value returned for each byte.
Since we are not checking for end of the file, the read() method reaches the end and the last integer of the output will be -1.
import java.io.DataInputStream; import java.io.File; import java.io.FileInputStream; import java.io.IOException; public class EndOfFileExample { public static void main(String[] args) { try{ File file = new File("sample.txt"); DataInputStream inputStream = new DataInputStream(new FileInputStream(file)); System.out.println(file.length()); for(int i=0; i<=file.length();i++) { int num = inputStream.read(); System.out.println(num); } } catch(IOException ioe) { ioe.printStackTrace(); } } }
Output
13 72 101 108 108 111 32 119 101 108 99 111 109 101 -1
Advertisements