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

Java中BufferedReader无法读取.test文件内容的问题求助

Hey Ben, let's tackle this issue where your BufferedReader is returning null immediately even though the .test file isn't empty. I've looked over your code and have a few likely causes and fixes to share:

First, Rule Out Basic File Issues

Before diving into reader logic, let's confirm the file itself is accessible and has content. Add these checks at the start of your method to eliminate simple problems:

File file = new File(fileName);
if (!file.exists()) {
    System.out.println("File not found: '" + fileName + "'");
    return null;
}
if (!file.canRead()) {
    System.out.println("File is not readable: '" + fileName + "'");
    return null;
}
System.out.println("File size: " + file.length() + " bytes"); // This will tell you if the file is actually empty

If the file size is greater than 0 but you're still getting null, the issue is likely with how you're handling the UTF-8 encoding.

The Most Likely Culprit: UTF-8 BOM (Byte Order Mark)

Many Windows tools (like Notepad) save UTF-8 files with a hidden BOM (bytes EF BB BF) at the start. The standard InputStreamReader doesn't handle this automatically, which can cause readLine() to behave unexpectedly—including returning null right away if the BOM is misinterpreted as the end of the file.

Updated Code with BOM Handling & Safe Resource Management

I've refactored your code to use try-with-resources (which automatically closes streams, preventing leaks) and added BOM detection logic:

import java.io.*;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;

public static ArrayList<String> readFile(String fileName) {
    File file = new File(fileName);

    // Basic file accessibility checks
    if (!file.exists()) {
        System.out.println("Unable to find file '" + fileName + "'");
        return null;
    }
    if (!file.canRead()) {
        System.out.println("File '" + fileName + "' is not readable");
        return null;
    }
    System.out.println("File size: " + file.length() + " bytes");

    try (PushbackInputStream pbStream = new PushbackInputStream(new FileInputStream(file), 3);
         BufferedReader reader = new BufferedReader(new InputStreamReader(pbStream, StandardCharsets.UTF_8))) {

        // Detect and skip UTF-8 BOM if present
        byte[] bomBytes = new byte[3];
        if (pbStream.read(bomBytes) != -1) {
            if (!(bomBytes[0] == (byte) 0xEF && bomBytes[1] == (byte) 0xBB && bomBytes[2] == (byte) 0xBF)) {
                // Not a UTF-8 BOM, push the bytes back to be read as content
                pbStream.unread(bomBytes);
            }
        }

        ArrayList<String> fileContents = new ArrayList<>();
        String line;
        while ((line = reader.readLine()) != null) {
            fileContents.add(line);
        }

        System.out.println("Successfully read " + fileContents.size() + " lines");
        return fileContents;

    } catch (FileNotFoundException ex) {
        System.out.println("Unable to open file '" + fileName + "'");
    } catch (IOException ex) {
        System.out.println("Error reading file '" + fileName + "': " + ex.getMessage());
        ex.printStackTrace(); // Print full stack trace to debug unexpected errors
    }
    return null;
}

Quick Test with Java NIO

To confirm if the issue is with your reader implementation, try using Java NIO's Files class which handles UTF-8 more robustly out of the box. Replace your current read logic with this snippet temporarily:

import java.nio.file.Files;
import java.nio.file.Paths;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;

// ...
try {
    List<String> lines = Files.readAllLines(Paths.get(fileName), StandardCharsets.UTF_8);
    System.out.println("NIO read " + lines.size() + " lines");
    return new ArrayList<>(lines);
} catch (IOException e) {
    e.printStackTrace();
}

If this works, it confirms the BOM or stream handling was the root problem.

Other Possible Checks

  • Double-check that the file isn't locked by another process (like a text editor that has it open)
  • Verify the file's actual encoding—if it's not UTF-8, specifying UTF-8 in the reader could cause parsing issues (though this usually leads to garbled text, not null)

Give these fixes a try, and let me know if you still run into issues!

内容的提问来源于stack exchange,提问作者Ben Marquez

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.28 07:31:10