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

Java读取文件第二行赋值变量时取值错误或返回null问题求解

问题根因
  • 代码内存在多次无效的br.readLine()调用,行计数完全错位:while条件里读一次行,循环体开头立刻再读一次,for循环里i=1时又读一次,单次循环就会消耗3行内容
  • while循环会一直执行到文件读取结束,br.readLine()返回null时才终止,最终lineTwo必然被赋值为null
  • 不需要遍历所有行,读取到目标第二行后直接终止操作即可
修复后代码
import java.io.File;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;

public class A9 {
    
    public static String readSecondLine(String path) {
        File newfile = new File(path);
        String lineTwo = null;
        int lineCount = 0;
        try(BufferedReader br = new BufferedReader(new FileReader(newfile))) {
            String currentLine;
            while((currentLine = br.readLine()) != null) {
                lineCount++;
                // 行号从1计数,匹配到第二行时赋值并退出循环
                if(lineCount == 2) {
                    lineTwo = currentLine;
                    break;
                }
            }
        }
        catch(IOException ex) {
            ex.printStackTrace();
        }
        return lineTwo;
    }

    public static void main(String[] args) {
        // 注意路径:开头带/是系统绝对路径,读取项目相对路径请去掉开头的/
        String path = "src/newtext.txt";
        System.out.println(readSecondLine(path));
    }
    
}
额外说明
  • 如果文件实际行数不足2行,方法会返回null,可根据业务需求补充对应的异常提示逻辑
  • 若文件路径确定为项目内资源,也可以改用类加载器的getResourceAsStream方法读取,避免不同运行环境下的路径适配问题

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.12 18:15:02