1. 程式人生 > >Java學習筆記14:Scanner讀取檔案

Java學習筆記14:Scanner讀取檔案

Scanner 不僅能從輸入流中讀取,也能從檔案中讀取,除了構建 Scanner 物件的方法,其他和上文給出的完全相同,以下案例從一個名為 test.txt 的檔案中讀取整數。

test.txt 檔案內容:

1
2
3
4
5
Fileio.java 檔案內容:

import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;

public class Fileio {
    public static void main(String[] args) throws FileNotFoundException {
        int[] arr=new int[10];
        int i=0;
        Scanner sc=new Scanner(new File("test.txt"));
        while(sc.hasNextInt()) {
            arr[i]=sc.nextInt();
            i++;
        }
        sc.close();
        System.out.printf("讀取了 %d 個數\n",i);
        for(int j=0;j<i;j++) {
            System.out.println(arr[j]);
        }
    }
}

輸出結果:

讀取了 5 個數
1
2
3
4
5