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

Java 8的FileReader/BufferedReader是否有问题?Eclipse运行无提示报错

Eclipse运行Java文件读取代码无输出且弹出异常提示的排查方案

首先明确一点:Java 8中的FileReader和BufferedReader本身没有问题,你遇到的情况基本是环境配置或文件路径导致的,咱们一步步来解决:

用户的代码与问题

我在Eclipse中编写了如下Java代码:

package fbread; 
import java.io.BufferedReader; 
import java.io.File; 
import java.io.FileNotFoundException; 
import java.io.FileReader; 
import java.io.IOException; 

public class Read { 
    public static void main(String[] args) { 
        File file = new File("text.txt"); 
        try { 
            FileReader fr = new FileReader(file); 
            BufferedReader br = new BufferedReader(fr); 
            String line; 
            while ((line = br.readLine()) != null) { 
                System.out.println(line); 
            } 
            br.close(); 
        } catch (FileNotFoundException e) { 
            System.out.println("File not found: " + file); 
        } catch (IOException e) { 
            System.out.println("Unable to read file: " + file); 
        } 
    } 
}

我认为这段代码完全正确,但在Eclipse中运行时,弹出了带红叉的灰色方块错误提示,无任何报错信息,程序也无输出。请问Java 8中的FileReader或BufferedReader是否存在问题?


排查步骤

1. 确认文件路径是否正确

你用的相对路径"text.txt"是相对于Eclipse项目的工作目录(也就是项目根目录,不是src文件夹)的:

  • 打开你的项目,检查项目根目录下有没有text.txt;
  • 如果没有,要么把文件移到项目根目录,要么改用绝对路径(比如"D:/Workspace/YourProject/text.txt")测试。

2. 检查Eclipse的运行配置

那个带红叉的灰色方块通常是运行时异常,但控制台没输出可能是配置问题:

  • 右键Read类 → Run As → Run Configurations;
  • 切换到Common标签,确保Standard Input and Output下的Allocate console是勾选状态;
  • 再到Arguments标签,确认Working directory是项目根目录(默认应该是,但如果被修改过就会出问题)。

3. 增强代码的错误排查能力

你的catch块只打印了简单提示,建议加上异常栈追踪,能看到更详细的错误信息:

catch (FileNotFoundException e) {
    System.out.println("File not found: " + file);
    e.printStackTrace(); // 打印完整异常栈,定位问题根源
} catch (IOException e) {
    System.out.println("Unable to read file: " + file);
    e.printStackTrace();
}

另外,Java 7+支持的try-with-resources语法更安全,无需手动关闭流,推荐替换:

try (FileReader fr = new FileReader(file);
     BufferedReader br = new BufferedReader(fr)) {
    String line;
    while ((line = br.readLine()) != null) {
        System.out.println(line);
    }
} catch (FileNotFoundException e) {
    System.out.println("File not found: " + file);
    e.printStackTrace();
} catch (IOException e) {
    System.out.println("Unable to read file: " + file);
    e.printStackTrace();
}

4. 清理Eclipse缓存

有时候Eclipse的编译缓存会出问题:

  • 右键项目 → Clean,清理后重新编译运行;
  • 或者手动删除项目下的bin目录,让Eclipse重新生成编译文件。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.19 03:11:02