Added some error handling.

This commit is contained in:
Andrew Lalis 2020-03-11 00:43:58 +01:00
parent f2e934620b
commit 724359d651
2 changed files with 20 additions and 13 deletions

View File

@ -7,6 +7,8 @@ import javax.swing.filechooser.FileNameExtensionFilter;
import javax.swing.text.JTextComponent;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.FileNotFoundException;
import java.io.IOException;
/**
* Listener for when a user clicks to load the contents of a file into a text component.
@ -32,7 +34,15 @@ public class LoadTextComponentFromFileListener implements ActionListener {
int result = fileChooser.showOpenDialog(textComponent);
if (result == JFileChooser.APPROVE_OPTION) {
this.textComponent.setText(FileLoader.readFile(fileChooser.getSelectedFile()));
try {
this.textComponent.setText(FileLoader.readFile(fileChooser.getSelectedFile()));
} catch (IOException exception) {
String message = "Could not read file.";
if (exception instanceof FileNotFoundException) {
message = "File not found.";
}
JOptionPane.showMessageDialog(this.textComponent, message, "Error Reading File", JOptionPane.WARNING_MESSAGE);
}
}
}
}

View File

@ -33,19 +33,16 @@ public class FileLoader {
* Reads a file into a string.
* @param selectedFile The file object, as it is often selected by a JFileChooser.
* @return The string containing the file, or an empty string.
* @throws IOException If the file could not be read.
*/
public static String readFile(File selectedFile) {
try (BufferedReader reader = new BufferedReader(new FileReader(selectedFile))) {
String line;
StringBuilder sb = new StringBuilder();
while ((line = reader.readLine()) != null) {
sb.append(line);
sb.append('\n');
}
return sb.toString();
} catch (IOException e) {
e.printStackTrace();
return "";
public static String readFile(File selectedFile) throws IOException {
BufferedReader reader = new BufferedReader(new FileReader(selectedFile));
String line;
StringBuilder sb = new StringBuilder();
while ((line = reader.readLine()) != null) {
sb.append(line);
sb.append('\n');
}
return sb.toString();
}
}