Java字符流案例如何读取文本

wen java案例 24

本文目录导读:

Java字符流案例如何读取文本

  1. 使用FileReader(基础方式)
  2. 使用BufferedReader(带缓冲的高效方式)
  3. 指定字符编码读取
  4. 使用Files工具类(Java 7+)
  5. 综合示例:读取并处理文件
  6. 性能对比和建议

我来详细介绍Java字符流读取文本的几种常见方式:

使用FileReader(基础方式)

import java.io.FileReader;
import java.io.IOException;
public class FileReaderExample {
    public static void main(String[] args) {
        FileReader reader = null;
        try {
            // 创建FileReader对象
            reader = new FileReader("test.txt");
            // 逐个字符读取
            int ch;
            while ((ch = reader.read()) != -1) {
                System.out.print((char) ch);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            // 关闭资源
            if (reader != null) {
                try {
                    reader.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}

使用BufferedReader(带缓冲的高效方式)

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
public class BufferedReaderExample {
    public static void main(String[] args) {
        // try-with-resources 自动关闭资源
        try (BufferedReader reader = new BufferedReader(new FileReader("test.txt"))) {
            String line;
            // 逐行读取
            while ((line = reader.readLine()) != null) {
                System.out.println(line);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

指定字符编码读取

import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
public class EncodingReaderExample {
    public static void main(String[] args) {
        try (BufferedReader reader = new BufferedReader(
                new InputStreamReader(
                    new FileInputStream("test.txt"), 
                    StandardCharsets.UTF_8))) {
            String line;
            while ((line = reader.readLine()) != null) {
                System.out.println(line);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

使用Files工具类(Java 7+)

import java.nio.file.Files;
import java.nio.file.Paths;
import java.io.IOException;
import java.util.List;
public class FilesReadExample {
    public static void main(String[] args) {
        try {
            // 读取所有行到List
            List<String> lines = Files.readAllLines(Paths.get("test.txt"));
            // 方法1:遍历行
            for (String line : lines) {
                System.out.println(line);
            }
            // 方法2:读取整个文件内容
            String content = new String(Files.readAllBytes(Paths.get("test.txt")));
            System.out.println(content);
            // 方法3:使用流式处理(Java 8+)
            Files.lines(Paths.get("test.txt"))
                 .filter(line -> !line.isEmpty())
                 .forEach(System.out::println);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

综合示例:读取并处理文件

import java.io.*;
import java.nio.file.*;
import java.util.stream.Stream;
public class AdvancedTextReader {
    // 方法1:使用BufferedReader逐行读取
    public static void readWithBufferedReader(String filePath) {
        System.out.println("=== 使用BufferedReader ===");
        try (BufferedReader br = new BufferedReader(new FileReader(filePath))) {
            String line;
            int lineNum = 1;
            while ((line = br.readLine()) != null) {
                System.out.printf("第%d行: %s%n", lineNum++, line);
            }
        } catch (IOException e) {
            System.err.println("读取文件失败: " + e.getMessage());
        }
    }
    // 方法2:使用Files类读取(现代方式)
    public static void readWithFilesAPI(String filePath) throws IOException {
        System.out.println("=== 使用Files API ===");
        // 读取所有行
        Files.readAllLines(Paths.get(filePath))
             .forEach(line -> System.out.println("内容: " + line));
    }
    // 方法3:使用Stream API(Java 8+)
    public static void readWithStream(String filePath) {
        System.out.println("=== 使用Stream API ===");
        try (Stream<String> lines = Files.lines(Paths.get(filePath))) {
            lines.map(String::toUpperCase)  // 转换为大写
                 .filter(s -> s.contains("JAVA"))  // 过滤包含JAVA的行
                 .forEach(System.out::println);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    // 方法4:读取指定编码的文件
    public static void readWithEncoding(String filePath) {
        System.out.println("=== 指定编码读取 ===");
        try (BufferedReader br = new BufferedReader(
                new InputStreamReader(
                    new FileInputStream(filePath), "GBK"))) {
            char[] buffer = new char[1024];
            int charsRead;
            StringBuilder content = new StringBuilder();
            while ((charsRead = br.read(buffer)) != -1) {
                content.append(buffer, 0, charsRead);
            }
            System.out.println("文件内容长度: " + content.length() + " 字符");
            System.out.println(content.toString());
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    public static void main(String[] args) {
        String filePath = "example.txt";
        // 创建测试文件
        try {
            Files.write(Paths.get(filePath), 
                "Hello Java!".getBytes());
            // 调用不同方法
            readWithBufferedReader(filePath);
            readWithFilesAPI(filePath);
            readWithStream(filePath);
            readWithEncoding(filePath);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

性能对比和建议

方法 适用场景 特点
FileReader 小文件、简单需求 基础,效率低
BufferedReader 大文件、需要缓冲 高效,推荐使用
InputStreamReader 需要指定编码 灵活,可控制编码
Files.readAllLines 小文件、快速读取 简洁,Java 7+
Files.lines 大文件、流式处理 懒加载,Java 8+

最佳实践建议:

  1. 一般文本文件推荐使用 BufferedReader
  2. 需要指定编码时使用 InputStreamReader 包装
  3. Java 8+ 可以使用 Files.lines() 配合Stream API
  4. 始终在try-with-resources中处理流资源
  5. 大文件避免使用 readAllLines()readAllBytes()

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