使用 JFileChooser 读取文件

Reading files with JFileChooser

我总是收到此代码的 NullPointerException

open.addActionListener(new ActionListener() {
    @Override
    public void actionPerformed(ActionEvent e) {
        modify = true;
        JFileChooser chooser = new JFileChooser();
        file = chooser.getSelectedFile();
        BufferedReader reader;
        StringBuilder sb = new StringBuilder();
        try {
            reader = new BufferedReader(new FileReader(file));
            String line = reader.readLine();
            while(line != null) {
                sb.append(line);
                sb.append(System.lineSeparator());
                line = reader.readLine();
            }
            text.setText(sb.toString());
        } 
        catch (FileNotFoundException e1) {
            e1.printStackTrace();
        }
        catch (IOException e1) {
            e1.printStackTrace();
        }
    }
});

reader = new BufferedReader(new FileReader(file));

行出现 NullPointerException

如何重组我的代码?

您实际上并没有选择文件。因此,选择器在查询所选文件名时是否返回 null。

您应该在创建实例后调用 chooser.showOpenDialog()chooser.showSaveDialog()

See how to here