I always get a NullPointerException with this code
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));
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.
You should call chooser.showOpenDialog()
or chooser.showSaveDialog()
after creating its instance.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.