如何在Java中讀取DataInputStream到檔案末尾,而無需捕獲EOFException?
在某些情況下讀取檔案內容時,會到達檔案末尾,在這種情況下會丟擲EOFException。
特別是,在使用輸入流物件讀取資料時會丟擲此異常。在其他情況下,到達檔案末尾時會丟擲特定值。
在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 {
//Reading data from user
Scanner sc = new Scanner(System.in);
System.out.println("Enter a String: ");
String data = sc.nextLine();
byte[] buf = data.getBytes();
//Writing it to a file using the DataOutputStream
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 {
//Reading data from user
Scanner sc = new Scanner(System.in);
System.out.println("Enter a String: ");
String data = sc.nextLine();
byte[] buf = data.getBytes();
//Writing it to a file using the DataOutputStream
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
廣告
資料結構
網路
關係資料庫管理系統(RDBMS)
作業系統
Java
iOS
HTML
CSS
Android
Python
C語言程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP