Java案例怎么读取TXT文件?

wen java案例 9

本文目录导读:

Java案例怎么读取TXT文件?

  1. 方法一:使用 BufferedReader(推荐)
  2. 方法二:使用 Files.readAllLines()(Java 8+)
  3. 方法三:使用 Scanner
  4. 方法四:使用 Files.lines()(Java 8+ Stream API)
  5. 方法五:使用 FileInputStream(读取二进制文件或指定编码)
  6. 注意事项
  7. 完整示例:带异常处理的工具类

在Java中读取TXT文件有多种方式,下面我为您介绍几种最常用的方法:

使用 BufferedReader(推荐)

这是最常用且高效的方式,适合读取大文件:

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
public class ReadTxtFile {
    public static void main(String[] args) {
        String filePath = "example.txt";
        try (BufferedReader reader = new BufferedReader(new FileReader(filePath))) {
            String line;
            while ((line = reader.readLine()) != null) {
                System.out.println(line);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

使用 Files.readAllLines()(Java 8+)

适合读取小文件,一次性读取所有行:

import java.nio.file.Files;
import java.nio.file.Paths;
import java.io.IOException;
import java.util.List;
public class ReadTxtFile {
    public static void main(String[] args) {
        String filePath = "example.txt";
        try {
            List<String> lines = Files.readAllLines(Paths.get(filePath));
            for (String line : lines) {
                System.out.println(line);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

使用 Scanner

适合需要按分隔符读取的场景:

import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class ReadTxtFile {
    public static void main(String[] args) {
        String filePath = "example.txt";
        try (Scanner scanner = new Scanner(new File(filePath))) {
            while (scanner.hasNextLine()) {
                String line = scanner.nextLine();
                System.out.println(line);
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
    }
}

使用 Files.lines()(Java 8+ Stream API)

适合需要流式处理的情况:

import java.nio.file.Files;
import java.nio.file.Paths;
import java.io.IOException;
import java.util.stream.Stream;
public class ReadTxtFile {
    public static void main(String[] args) {
        String filePath = "example.txt";
        try (Stream<String> lines = Files.lines(Paths.get(filePath))) {
            lines.forEach(System.out::println);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

使用 FileInputStream(读取二进制文件或指定编码)

import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.io.IOException;
public class ReadTxtFile {
    public static void main(String[] args) {
        String filePath = "example.txt";
        try (BufferedReader reader = new BufferedReader(
                new InputStreamReader(new FileInputStream(filePath), "UTF-8"))) {
            String line;
            while ((line = reader.readLine()) != null) {
                System.out.println(line);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

注意事项

  1. 资源管理:使用 try-with-resources(Java 7+)自动关闭流
  2. 文件编码:处理中文时建议指定 UTF-8 编码
  3. 异常处理:处理 FileNotFoundException 和 IOException
  4. 路径问题:可以使用相对路径或绝对路径

完整示例:带异常处理的工具类

import java.io.*;
import java.nio.charset.StandardCharsets;
import java.nio.file.*;
import java.util.*;
public class TxtFileReader {
    // 读取为字符串列表
    public static List<String> readLines(String filePath) {
        List<String> lines = new ArrayList<>();
        try (BufferedReader reader = Files.newBufferedReader(
                Paths.get(filePath), StandardCharsets.UTF_8)) {
            String line;
            while ((line = reader.readLine()) != null) {
                lines.add(line);
            }
        } catch (IOException e) {
            System.err.println("读取文件失败: " + e.getMessage());
        }
        return lines;
    }
    // 读取为整个字符串
    public static String readAllText(String filePath) {
        try {
            return new String(Files.readAllBytes(Paths.get(filePath)), 
                    StandardCharsets.UTF_8);
        } catch (IOException e) {
            System.err.println("读取文件失败: " + e.getMessage());
            return "";
        }
    }
    // 使用示例
    public static void main(String[] args) {
        String filePath = "data.txt";
        // 按行读取
        List<String> lines = readLines(filePath);
        lines.forEach(System.out::println);
        // 读取全部内容
        String content = readAllText(filePath);
        System.out.println(content);
    }
}

选择哪种方法取决于您的具体需求:

  • 大文件:使用 BufferedReader
  • 小文件:使用 Files.readAllLines()
  • 流式处理:使用 Files.lines()
  • 需要编码控制:使用 FileInputStream

抱歉,评论功能暂时关闭!