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

Java Swing点击JButton加载文本到JList报NumberFormatException求助

解决Java加载JList时的NumberFormatException问题

先直接点明你遇到的错误根源:你的加载代码错误地默认文本文件第一行是条目数量的数字,但实际上你的文本文件里第一行是保存的书籍数据1-java-3-4,把这个非数字字符串强行转成Integer自然会抛出NumberFormatException;如果文件存在空行,还会触发For input string: ""的异常分支。

接下来我们一步步修复问题:

1. 先修正添加数据的小瑕疵

看你的btAddBookActionPerformed方法,拼接数据时Quantity+"- "+Price多了一个空格,这会导致保存的数据里混入多余空格,后续加载或处理容易出问题,先把这个空格去掉:

listmodel.addElement(BookId+"-"+BookName+"-"+Quantity+"-"+Price);

2. 补充正确的保存数据代码

你没提供保存按钮的实现,这是关键缺失项。我们需要把JList里的所有数据逐行写入文本文件:

private void btSaveDBActionPerformed(java.awt.event.ActionEvent evt) {
    BufferedWriter bw = null;
    try {
        bw = new BufferedWriter(new FileWriter("BookList.txt"));
        // 遍历ListModel里的所有元素,逐行写入文件
        for (int i = 0; i < listmodel.getSize(); i++) {
            bw.write(listmodel.getElementAt(i).toString());
            bw.newLine(); // 每条数据占一行
        }
        JOptionPane.showMessageDialog(null, "数据保存成功!");
    } catch (IOException e) {
        e.printStackTrace();
        JOptionPane.showMessageDialog(null, "保存失败:" + e.getMessage());
    } finally {
        try {
            if (bw != null) bw.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

3. 彻底修复加载数据的逻辑

你的加载逻辑完全错了——我们的保存逻辑并没有写入条目数量,所以不需要先读取数字,直接逐行读取文件内容直到结束即可:

private void btLoadDBActionPerformed(java.awt.event.ActionEvent evt) {
    BufferedReader br = null;
    try {
        br = new BufferedReader(new FileReader("BookList.txt"));
        listmodel.clear(); // 先清空现有数据,避免重复加载
        String line;
        // 逐行读取,直到line为null(文件读取完毕)
        while ((line = br.readLine()) != null) {
            // 跳过空行,避免空字符串引发异常
            if (!line.trim().isEmpty()) {
                listmodel.addElement(line);
            }
        }
        booklist.setModel(listmodel);
        JOptionPane.showMessageDialog(null, "数据加载成功!");
    } catch (Exception e) {
        e.printStackTrace();
        JOptionPane.showMessageDialog(null, "加载失败:" + e.getMessage());
    } finally {
        try {
            if (br != null) br.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

额外优化建议

  • 输入验证可以更严谨:比如Quantity和Price应该是数字类型,添加时可以先尝试转成Integer/Double,避免非法数据存入。
  • 替换文本框的默认值逻辑:可以用setToolTipText设置输入提示,而不是把"Type Here"作为默认值,这样判断空值更简单,比如直接用txtBookID.getText().trim().isEmpty()。

内容的提问来源于stack exchange,提问作者An Mạnh

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.15 06:47:23