English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
In some cases, when reading the content of the file, if the end of the file is reached in this case, EOFException will be thrown.
Especially, this exception is thrown when reading data with Input stream objects. In other cases, a specific value will be thrown when reaching the end of the file.
In the DataInputStream class, it provides various methods, such asreadboolean()
,readByte()
,readChar()
Etc., the original value read. When using these methods to read data from the file, EOFException will be thrown when reaching the end of the file.
The following program demonstrates how to handle EOFException in Java.
import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.FileInputStream; import java.io.FileOutputStream; import java.util.Scanner; public class AIOBSample { public static void main(String[] args) throws Exception { //Read data from the user Scanner sc = new Scanner(System.in); System.out.println("Enter a String: "); String data = sc.nextLine(); byte[] buf = data.getBytes(); //Write it to the file DataOutputStream dos = new DataOutputStream(new FileOutputStream("D:\\data.txt")); for (byte b : buf) { dos.writeChar(b); } dos.flush(); //Reading from the above created file using readChar() method DataInputStream dis = new DataInputStream(new FileInputStream("D:\\data.txt")); while(true) { char ch; ch = dis.readChar(); System.out.print(ch); } } }
Output Result
Enter a String: hello how are you helException in thread "main" lo how are youjava.io.EOFException at java.io.DataInputStream.readChar(Unknown Source) at MyPackage.AIOBSample.main(AIOBSample.java:27)
You cannot useDataInputStreamThe class reads the content of the file until it reaches the end of the file. You can use other subclasses of the InputStream interface if needed.
In the following example, we use the FileInputStream class instead of DataInputStream to rewrite the above program to read data from the file.
import java.io.DataOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.util.Scanner; public class AIOBSample { public static void main(String[] args) throws Exception { //Read data from the user Scanner sc = new Scanner(System.in); System.out.println("Enter a String: "); String data = sc.nextLine(); byte[] buf = data.getBytes(); //Write it to the file DataOutputStream dos = new DataOutputStream(new FileOutputStream("D:\\data.txt")); for (byte b : buf) { dos.writeChar(b); } dos.flush(); //Reading from the above created file using readChar() method File file = new File("D:\\data.txt"); FileInputStream fis = new FileInputStream(file); byte b[] = new byte[(int) file.length()]; fis.read(b); System.out.println("contents of the file: ");+new String(b)); } }
Output Result
Enter a String: Hello how are you contents of the file: H e l l o h o w a r e y o u