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

Java Swing如何从TXT文件提取指定数据到JComboBox

解决JComboBox仅显示menu.txt中食物名称的问题

你当前的代码直接将文件整行内容添加到JComboBox中,而原文件每行包含序号、食物名称、价格三个字段(用多个空白字符分隔),导致下拉框显示了整行的合并内容。要仅显示食物名称,需要提取每行的第二部分字段。

核心思路

通过正则表达式分割每行字符串,精准提取中间的食物名称:

  • 用\\s+匹配一个或多个空白字符(空格、制表符等)作为分隔符,将每行拆分为数组
  • 数组的第二个元素(索引为1)即为目标食物名称
  • 同时处理空行和格式异常的情况,避免程序报错

修改后的代码(Stream API简化版)

public void fillComboFromTxtFile() {
    File file = new File("Menu.txt");
    // try-with-resources自动关闭流,避免资源泄漏
    try (BufferedReader br = new BufferedReader(new FileReader(file))) {
        br.lines()
          .map(String::trim) // 去除每行首尾空白
          .filter(line -> !line.isEmpty()) // 过滤空行
          .map(line -> line.split("\\s+")) // 按多个空白分割每行
          .filter(parts -> parts.length >= 2) // 确保格式合法
          .map(parts -> parts[1]) // 提取食物名称
          .forEach(cbName::addItem); // 添加到下拉框
    } catch (FileNotFoundException ex) {
        Logger.getLogger(Order.class.getName()).log(Level.SEVERE, null, ex);
    } catch (IOException ex) {
        Logger.getLogger(Order.class.getName()).log(Level.SEVERE, null, ex);
    }
}

传统循环版代码(兼容低版本Java)

public void fillComboFromTxtFile() {
    File file = new File("Menu.txt");
    BufferedReader br = null;
    try {
        br = new BufferedReader(new FileReader(file));
        String line;
        while ((line = br.readLine()) != null) {
            line = line.trim();
            if (line.isEmpty()) continue; // 跳过空行
            
            String[] parts = line.split("\\s+");
            if (parts.length >= 2) { // 确保分割后有足够字段
                cbName.addItem(parts[1]);
            }
        }
    } catch (FileNotFoundException ex) {
        Logger.getLogger(Order.class.getName()).log(Level.SEVERE, null, ex);
    } catch (IOException ex) {
        Logger.getLogger(Order.class.getName()).log(Level.SEVERE, null, ex);
    } finally {
        // 手动关闭流
        if (br != null) {
            try {
                br.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}

代码说明

  1. 空白字符兼容:\\s+可以匹配任意数量的空格或制表符,完美适配原文件的分隔格式
  2. 异常处理:补充捕获IOException,覆盖所有可能的IO异常场景
  3. 健壮性:过滤空行、校验分割结果长度,避免因文件格式问题导致程序崩溃

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.21 22:24:20