简体   繁体   English

使用JFileChooser读取文件

[英]Reading files with JFileChooser

I always get a NullPointerException with this code 我总是用此代码获得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();
        }
    }
});

NullPointerException on the line reader = new BufferedReader(new FileReader(file)); 在线reader = new BufferedReader(new FileReader(file));上的NullPointerException reader = new BufferedReader(new FileReader(file));

How can I reorganize my code? 如何重新组织我的代码?

You didn't actually choose the file. 您实际上并没有选择文件。 Therefore is the chooser returning null when quering it for that selected file name. 因此,当查询该选定文件名时,选择器返回null。

You should call chooser.showOpenDialog() or chooser.showSaveDialog() after creating its instance. 创建实例后,应调用chooser.showOpenDialog()chooser.showSaveDialog()

See how to here 了解如何前往

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM