English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
파일의 내용을 읽을 때 일부 경우에 파일의 끝에 도달하게 되면 EOFException이 발생합니다.
특히, Input 스트림 객체를 사용하여 데이터를 읽을 때 이 예외가 발생합니다. 다른 경우에는 파일의 끝에 도달할 때 특정 값을 던집니다.
DataInputStream 클래스는 다양한 메서드를 제공합니다.readboolean()
,readByte()
,readChar()
예를 들어, 파일의 끝에 도달할 때 EOFException이 발생합니다.
다음 프로그램은 Java에서 EOFException을 처리하는 방법을 보여줍니다。
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 { //사용자로부터 데이터를 읽기 Scanner sc = new Scanner(System.in); System.out.println("문자열을 입력하세요:"); String data = sc.nextLine(); byte[] buf = data.getBytes(); //그것을 파일에 쓰기 DataOutputStream dos = new DataOutputStream(new FileOutputStream("D:\\data.txt")); for(byte b:buf) { dos.writeChar(b); } dos.flush(); //위에서 생성된 파일에서 readChar() 메서드를 사용하여 읽기 DataInputStream dis = new DataInputStream(new FileInputStream("D:\data.txt")); while(true) { char ch; ch = dis.readChar(); System.out.print(ch); } } }
출력 결과
문자열을 입력하세요: 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)
DataInputStream을 읽을 때는 예외를 잡지 않을 수 없습니다.DataInputStream클래스는 파일의 끝에 도달하기 전까지 파일의 내용을 읽습니다. 필요하다면 InputStream 인터페이스의 다른 서브클래스를 사용할 수 있습니다。
다음 예제에서는 FileInputStream 클래스를 DataInputStream 대신 사용하여 데이터를 파일에서 읽기 위해 위의 프로그램을 다시 작성했습니다。
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 { //사용자로부터 데이터를 읽기 Scanner sc = new Scanner(System.in); System.out.println("문자열을 입력하세요:"); String data = sc.nextLine(); byte[] buf = data.getBytes(); //그것을 파일에 쓰기 DataOutputStream dos = new DataOutputStream(new FileOutputStream("D:\\data.txt")); for(byte b:buf) { dos.writeChar(b); } dos.flush(); //위에서 생성된 파일에서 readChar() 메서드를 사용하여 읽기 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("파일 내용: ");+new String(b)); } }
출력 결과
문자열을 입력하세요: Hello how are you 파일 내용: H e l l o h o w a r e y o u