如何使用 Scanner 類讀取檔案內容?
從 Java 1.5 開始引入了 Scanner 類。此類接受 File、InputStream、Path 和 String 物件,使用正則表示式逐個讀取所有原始資料型別和字串(來自給定源)。預設情況下,空格被視為分隔符(將資料分成標記)。
使用此類提供的 nextXXX() 方法讀取源中的各種資料型別。
讀取檔案內容 -
要讀取檔案內容,**Scanner** 類提供了各種建構函式。
| 序號 | 建構函式及描述 |
|---|---|
| 1 | Scanner(File source) 用於讀取給定 File 物件表示的檔案中的資料。 |
| 2 | Scanner(InputStream source) 用於讀取指定 InputStream 中的資料。 |
| 3 | Scanner(Path source) 用於讀取指定檔案物件表示的檔案中的資料。 |
假設我們在路徑 D:\ 中有一個名為 myFile.txt 的檔案,如下所示 -

以下示例演示瞭如何使用上述建構函式從該檔案讀取資料。
示例 - 檔案物件
- 建立一個表示所需檔案的 File 物件。
- 透過傳遞上面建立的檔案物件建立一個 Scanner 類。
- hasNext() 驗證檔案是否還有另一行,nextLine() 方法讀取並返回檔案中的下一行。使用這些方法讀取檔案內容。
import java.io.File;
import java.util.Scanner;
public class ContentsOfFile {
public static void main(String args[]) throws Exception {
//Creating the File object
File file = new File("D:\MyFile.txt");
//Creating a Scanner object
Scanner sc = new Scanner(file);
//StringBuffer to store the contents
StringBuffer sb = new StringBuffer();
//Appending each line to the buffer
while(sc.hasNext()) {
sb.append(" "+sc.nextLine());
}
System.out.println(sb);
}
}輸出
Hi welcome to Tutorialspoint ....
示例 - 輸入流物件
- 透過將所需檔案的路徑作為引數傳遞給其建構函式,建立一個 FileInputStream 物件。
- 透過傳遞上面建立的 FileInputStream 物件建立一個 Scanner 類。
- hasNext() 驗證檔案是否還有另一行,nextLine() 方法讀取並返回檔案中的下一行。使用這些方法讀取檔案內容。
import java.io.FileInputStream;
import java.io.InputStream;
import java.util.Scanner;
public class ContentsOfFile {
public static void main(String args[]) throws Exception {
//Creating the File object
InputStream inputStream = new FileInputStream("D:\MyFile.txt");
//Creating a Scanner object
Scanner sc = new Scanner(inputStream);
//StringBuffer to store the contents
StringBuffer sb = new StringBuffer();
//Appending each line to the buffer
while(sc.hasNext()) {
sb.append(" "+sc.nextLine());
}
System.out.println(sb);
}
}輸出
Hi welcome to Tutorialspoint ....
廣告
資料結構
網路
關係資料庫管理系統
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP