You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Java使用BufferedReader读取TXT文件异常问题求助

Troubleshooting BufferedReader Issues with TXT Files in Java

It sounds like you're hitting some tricky inconsistencies when reading TXT files with BufferedReader—even though all files seem identical in path, encoding, and attributes. Let's break down the most likely causes and fixes for this behavior:

1. Reusing the Same BufferedReader Instance for Multiple Streams

Looking at your code snippet, you're using a br variable to read user input (shelf = br.readLine()), then presumably reusing that same br to read the file. This is a critical mistake.

When you initialize a BufferedReader with System.in (for user input), it’s tied to that input stream. Reassigning it to read a file later can leave leftover stream state, leading to unexpected reads like empty lines, nulls, or skipped content.

Fix: Always create a separate BufferedReader for file reading:

// For user input (separate instance)
BufferedReader inputBr = new BufferedReader(new InputStreamReader(System.in));
System.out.println("\r\nChose desired shelf:"); 
String shelf = inputBr.readLine(); 

// For file reading (another dedicated instance)
FileReader fr = new FileReader("D:\\admir\\MyBookLibrary\\"+shelf+"\\Info.txt"); 
BufferedReader fileBr = new BufferedReader(fr);

// Read the file line by line
String line;
while ((line = fileBr.readLine()) != null) {
    System.out.println(line);
}

// Clean up streams
fileBr.close();
inputBr.close();

2. Byte Order Mark (BOM) in Some Files

Even if encoding is set to UTF-8, some editors (like Windows Notepad) add a hidden BOM character at the start of files. BufferedReader doesn’t automatically skip this, so the first line might appear empty or garbled, and subsequent lines might read incorrectly.

Fix: Check for and skip the BOM when reading:

BufferedReader fileBr = new BufferedReader(new InputStreamReader(
    new FileInputStream("D:\\admir\\MyBookLibrary\\"+shelf+"\\Info.txt"), StandardCharsets.UTF_8));

// Skip BOM if present
fileBr.mark(1);
if (fileBr.read() != '\ufeff') {
    fileBr.reset();
}

// Now read lines normally
String line;
while ((line = fileBr.readLine()) != null) {
    System.out.println(line);
}

3. Inconsistent Line Endings

Files created on different operating systems might use different line endings:

  • Windows: CRLF (\r\n)
  • Unix/Linux/macOS: LF (\n)
  • Old macOS: CR (\r)

While BufferedReader should handle all these, mixed line endings in some files can cause misinterpretation, leading to empty strings or skipped content.

Fix: Normalize line endings when reading, or ensure all files use the same format. You can also read the entire file as a string and split on any line ending pattern:

String content = new String(Files.readAllBytes(Paths.get("D:\\admir\\MyBookLibrary\\"+shelf+"\\Info.txt")), StandardCharsets.UTF_8);
String[] lines = content.split("\\r?\\n|\\r"); // Handles all line ending types
for (String line : lines) {
    System.out.println(line);
}

4. Unclosed Streams from Previous Reads

If you’re reading multiple files without closing the BufferedReader/FileReader each time, the underlying file handle might not release properly. This can lead to leftover buffer data or incomplete reads for subsequent files.

Fix: Use try-with-resources to automate stream closure (safer and cleaner):

try (BufferedReader fileBr = new BufferedReader(new FileReader("D:\\admir\\MyBookLibrary\\"+shelf+"\\Info.txt"))) {
    String line;
    while ((line = fileBr.readLine()) != null) {
        System.out.println(line);
    }
} catch (IOException e) {
    e.printStackTrace();
}

The try-with-resources block closes the reader automatically, even if an exception occurs.

5. Hidden Control Characters in Files

Some files might contain invisible control characters (like null bytes or vertical tabs) that cause readLine() to terminate early or return empty lines. You can verify this with a hex editor to spot non-printable characters.

Fix: Clean lines by filtering out non-printable characters when reading:

String line;
while ((line = fileBr.readLine()) != null) {
    // Remove non-printable characters except whitespace and valid text
    String cleanedLine = line.replaceAll("[^\\p{Print}\\p{Space}]", "");
    System.out.println(cleanedLine);
}

内容的提问来源于stack exchange,提问作者Tabby Auguste

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.26 10:00:57