溫馨提示×

Java怎么讀取txt文件中的內(nèi)容

小億
148
2024-04-01 20:25:06
欄目: 編程語言

要讀取一個txt文件中的內(nèi)容,可以使用Java中的File類和Scanner類。下面是一個簡單的示例代碼:

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

public class ReadFile {
    public static void main(String[] args) {
        try {
            File file = new File("file.txt");
            Scanner scanner = new Scanner(file);
            
            while (scanner.hasNextLine()) {
                String line = scanner.nextLine();
                System.out.println(line);
            }
            
            scanner.close();
        } catch (FileNotFoundException e) {
            System.err.println("文件未找到");
        }
    }
}

在上面的代碼中,首先創(chuàng)建一個File對象來表示要讀取的txt文件,然后創(chuàng)建一個Scanner對象來讀取文件內(nèi)容。使用while循環(huán)來逐行讀取文件內(nèi)容,并打印出來。最后別忘了關(guān)閉Scanner對象。

0