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 javax.swing.text.JTextComponent;
import java.awt.event.ActionEvent; import java.awt.event.ActionEvent;
import java.awt.event.ActionListener; 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. * 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); int result = fileChooser.showOpenDialog(textComponent);
if (result == JFileChooser.APPROVE_OPTION) { if (result == JFileChooser.APPROVE_OPTION) {
try {
this.textComponent.setText(FileLoader.readFile(fileChooser.getSelectedFile())); 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,9 +33,10 @@ public class FileLoader {
* Reads a file into a string. * Reads a file into a string.
* @param selectedFile The file object, as it is often selected by a JFileChooser. * @param selectedFile The file object, as it is often selected by a JFileChooser.
* @return The string containing the file, or an empty string. * @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) { public static String readFile(File selectedFile) throws IOException {
try (BufferedReader reader = new BufferedReader(new FileReader(selectedFile))) { BufferedReader reader = new BufferedReader(new FileReader(selectedFile));
String line; String line;
StringBuilder sb = new StringBuilder(); StringBuilder sb = new StringBuilder();
while ((line = reader.readLine()) != null) { while ((line = reader.readLine()) != null) {
@ -43,9 +44,5 @@ public class FileLoader {
sb.append('\n'); sb.append('\n');
} }
return sb.toString(); return sb.toString();
} catch (IOException e) {
e.printStackTrace();
return "";
}
} }
} }