如何在不捕获Java中的EOFException的情况下读取DataInputStream到最后?
在某些情况下读取文件的内容时,在这种情况下将到达文件末尾,将引发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("Enter a String: "); 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(); //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); } } }
输出结果
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)
读取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("Enter a String: "); 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(); //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)); } }
输出结果
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