當 read() 方法在 java 中到達檔案末尾時會返回什麼值?
輸入流類的read()方法逐位元組讀取給定檔案的內容,並以整數形式返回讀取位元組的 ASCII 值。在讀取檔案時,如果它到達檔案末尾,則此方法將返回 -1。
示例
假設我們在當前目錄中有一個文字檔案 (sample.txt),其中有簡單的文字“Hello welcome”。以下 Java 程式使用 read() 方法逐位元組地讀取檔案內容,並列印為每個位元組返回的整數值。
由於我們沒有檢查檔案末尾,因此 read() 方法到達末尾,輸出的最後一個整數將為 -1。
import java.io.DataInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
public class EndOfFileExample {
public static void main(String[] args) {
try{
File file = new File("sample.txt");
DataInputStream inputStream = new DataInputStream(new FileInputStream(file));
System.out.println(file.length());
for(int i=0; i<=file.length();i++) {
int num = inputStream.read();
System.out.println(num);
}
} catch(IOException ioe) {
ioe.printStackTrace();
}
}
}輸出
13 72 101 108 108 111 32 119 101 108 99 111 109 101 -1
廣告
資料結構
網路
關係型資料庫管理系統
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP