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

Java GUI均值计算程序遇FileNotFoundException及资源泄漏问题求助

问题修复:文件均值计算程序的异常与资源问题

核心问题分析

你的代码存在三个关键问题:

  1. 未处理FileNotFoundException:创建Scanner读取文件时,若文件不存在或路径错误会抛出该异常,当前代码未捕获或声明抛出
  2. Scanner资源泄漏:使用完Scanner后未关闭,导致资源无法正常释放
  3. 潜在除零异常:若文件无有效数字,list_of_numbers为空,执行sum / list_of_numbers.size()会抛出ArithmeticException

修正后的代码

1. 修复后的MainClass

import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
import java.util.ArrayList;
import javax.swing.JOptionPane;

public class MainClass {

    public static double mean_file(String file_name) throws FileNotFoundException {
        /*
         * 计算文本文件中数字的平均值
         */
        File data = new File(file_name);
        double sum = 0;
        ArrayList<Integer> list_of_numbers = new ArrayList<>();
        
        // 使用try-with-resources自动关闭Scanner,避免资源泄漏
        try (Scanner read = new Scanner(data)) {
            while (read.hasNextLine()) {
                try {
                    // 去除首尾空格,避免因空格导致的格式转换错误
                    int nb = Integer.parseInt(read.nextLine().trim());
                    list_of_numbers.add(nb);
                } catch (NumberFormatException n) {
                    JOptionPane.showOptionDialog(null, "文件内容错误", "文件必须每行仅包含一个数字!", JOptionPane.ERROR_MESSAGE, null, null, "OK");
                }
            }
        }

        // 处理空列表情况,避免除零异常
        if (list_of_numbers.isEmpty()) {
            JOptionPane.showOptionDialog(null, "计算失败", "文件中无有效数字!", JOptionPane.WARNING_MESSAGE, null, null, "OK");
            return 0.0; // 可根据需求调整默认返回值
        }

        // 增强for循环简化遍历逻辑
        for (int num : list_of_numbers) {
            sum += num;
        }
        return sum / list_of_numbers.size();
    }
}

2. 修复后的GUI代码(TextFileMean)

import java.awt.EventQueue;
import java.io.FileNotFoundException;

import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JTextField;
import javax.swing.JButton;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import javax.swing.JTextArea;
import javax.swing.JOptionPane;

public class TextFileMean {

    private JFrame frame;
    private JLabel FileNameLabel;
    private JTextField FileNameEntry;
    private JButton OpenFileBtn;
    private JTextArea Result;

    public static void main(String[] args) {
        EventQueue.invokeLater(() -> {
            try {
                TextFileMean window = new TextFileMean();
                window.frame.setVisible(true);
            } catch (Exception e) {
                e.printStackTrace();
            }
        });
    }

    public TextFileMean() {
        initialize();
    }

    private void initialize() {
        frame = new JFrame();
        frame.setBounds(100, 100, 450, 300);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.getContentPane().setLayout(null);
        
        FileNameLabel = new JLabel("文件名");
        FileNameLabel.setBounds(65, 92, 71, 16);
        frame.getContentPane().add(FileNameLabel);
        
        FileNameEntry = new JTextField();
        FileNameEntry.setBounds(148, 87, 230, 26);
        frame.getContentPane().add(FileNameEntry);
        FileNameEntry.setColumns(10);
        
        OpenFileBtn = new JButton("打开文件");
        OpenFileBtn.addMouseListener(new MouseAdapter() {
            @Override
            public void mouseClicked(MouseEvent e) {
                try {
                    double mean = MainClass.mean_file(FileNameEntry.getText());
                    // 格式化输出保留两位小数,提升用户体验
                    Result.setText(String.format("%.2f", mean));
                } catch (FileNotFoundException fnf) {
                    JOptionPane.showOptionDialog(null, "文件错误", "未找到指定文件,请检查路径!", JOptionPane.ERROR_MESSAGE, null, null, "OK");
                }
            }
        });
        OpenFileBtn.setBounds(164, 125, 117, 29);
        frame.getContentPane().add(OpenFileBtn);
        
        Result = new JTextArea();
        Result.setBounds(165, 191, 100, 30);
        frame.getContentPane().add(Result);
    }
}

关键修改说明

  • 资源泄漏修复:使用try-with-resources语法创建Scanner,JVM会自动在代码块结束后关闭资源,无需手动调用close()
  • 异常处理完善:
    • 在mean_file方法中声明抛出FileNotFoundException,由GUI层捕获并提示用户文件不存在
    • 增加空列表判断,避免除零异常,同时给用户明确提示
    • 读取行时调用trim(),避免因行首/行尾空格导致的格式转换错误
  • 代码优化:使用增强for循环遍历列表简化代码;格式化均值输出为两位小数,提升用户体验

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.15 05:14:59