Search code examples
javanullpointerexception

nullpointerexception error on cancel or closing dialog


My problem is when my showopendialog appears and I press cancel or the X on the right corner instead of loading some text in my textarea, the console shows the error of nullpointexception on my line String filename=f.getAbsolutePath();

My action open is on a menu bar.

Thank you.

JFileChooser flcFile = new JFileChooser("c:\\");
flcFile.showOpenDialog(null);
File f = flcFile.getSelectedFile();
String filename=f.getAbsolutePath();

    try {
        FileReader reader = new FileReader(filename);
        BufferedReader br = new BufferedReader(reader);
        txtPersonal.read(br, null);

        br.close();
        txtPersonal.requestFocus();

    }
     catch(Exception e)
     {
         JOptionPane.showMessageDialog(null, e);
     }

Solution

  • If you close without selecting a file, you can't get the absolute path of the file. Always check if a file has been selected by the user by checking the value returned by the showOpenDialog() method. Only get the absolute path after this check.

    Useful reading: The JFileChooser docs.

    JFileChooser flcFile = new JFileChooser("c:\\");
    int result = flcFile.showOpenDialog(null);
    if (result == JFileChooser.APPROVE_OPTION) {
        File f = flcFile.getSelectedFile();
        String filename = f.getAbsolutePath();
    
        try {
            FileReader reader = new FileReader(filename);
            BufferedReader br = new BufferedReader(reader);
            txtPersonal.read(br, null);
    
            br.close();
            txtPersonal.requestFocus();
    
        } catch (Exception e) {
            JOptionPane.showMessageDialog(null, e);
        }
    }