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