You need to enable JavaScript to run this app. Java设置FileWriter追加参数后执行sc.nextLong()无响应问题求助
优惠活动
大模型
产品
解决方案
定价
更多

Java设置FileWriter追加参数后执行sc.nextLong()无响应问题求助

问题根因
  • 核心卡死原因是Cliente类的Salvar方法存在无限死循环:
    统计文件行数的循环里仅做了计数,没有持续读取下一行内容,只要文件有内容,linha变量永远不为null,程序会一直卡在循环里无法继续执行。
    为什么仅开启追加模式时才出问题?因为默认覆盖模式下FileWriter会先清空目标文件内容,第一次读取br.readLine()直接返回null,循环不会执行就不会触发死循环;而追加模式不会清空原有文件,只要文件有内容就会进入死循环卡死。
  • 额外潜在死循环:ConsultaListaClientes方法的遍历输出逻辑也存在一模一样的问题,后续调用查询客户列表时同样会卡死。
  • 其他关联问题:文件流资源用完没有关闭,会导致写入的内容无法落地到文件、文件锁占用等异常。
解决方案

1. 修正Salvar方法

调整逻辑顺序:先判断/创建文件、读取行数统计完后关闭读资源,再开启追加写入流,写完后主动关闭写资源,同时修正计数循环逻辑:

public String Salvar() {
    String diretorio = "C:\\Users\\Ricardo\\Desktop\\LP2Teste\\clientes.txt";
    BufferedReader br = null;
    PrintWriter pw = null;
    try {
        File file = new File(diretorio);
        if (!file.exists()) {
            file.createNewFile();
        }
        // 先读文件统计行数
        FileReader fr = new FileReader(diretorio);
        br = new BufferedReader(fr);
        String linha = br.readLine();
        int numLinha = 0;
        while (linha != null) {
            numLinha++;
            linha = br.readLine(); // 新增:读取下一行,避免死循环
        }
        br.close(); // 读完立即关闭读资源

        // 再开追加写入流
        FileWriter fw = new FileWriter(diretorio, true);
        pw = new PrintWriter(fw);
        String codigo = "0" + Integer.toString(numLinha + 1); // 注意:原有行数是numLinha,新记录是numLinha+1,修正原有重复编码问题
        this.setCodigo(codigo);
        pw.println(this.getCodigo() + "-" + this.getNome() + "-" + this.getDocumento() +
                "-" + this.getEndereco() + "-" + this.getTelefone() + "-" + this.getEmail());
        pw.flush();
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        // 统一关闭资源避免泄漏
        try {
            if (br != null) br.close();
            if (pw != null) pw.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    return null;
}

2. 修正ConsultaListaClientes方法

public String ConsultaListaClientes() {
    String diretorio = "C:\\Users\\Ricardo\\Desktop\\LP2Teste\\clientes.txt";
    BufferedReader br = null;
    try {
        FileReader fr = new FileReader(diretorio);
        br = new BufferedReader(fr);
        String linha = br.readLine();
        while (linha != null) {
            System.out.println(linha);
            linha = br.readLine(); // 新增:读取下一行,避免死循环
        }
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        try {
            if (br != null) br.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    return null;
}

3. 可选优化:修正Scanner输入逻辑

现有代码中sc.nextLong()、sc.next()执行后会留下换行符,后续调用sc.nextLine()会读取到空字符串,建议每次调用完next()、nextLong()、nextInt()之后加一行sc.nextLine()吞掉残留的换行符,避免输入逻辑异常。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.16 05:27:01