From 724359d651f589b0e29a6c93ee70baea63ecdfb2 Mon Sep 17 00:00:00 2001 From: Andrew Lalis Date: Wed, 11 Mar 2020 00:43:58 +0100 Subject: [PATCH] Added some error handling. --- .../LoadTextComponentFromFileListener.java | 12 ++++++++++- .../java/com/gyrobian/util/FileLoader.java | 21 ++++++++----------- 2 files changed, 20 insertions(+), 13 deletions(-) diff --git a/src/main/java/com/gyrobian/listener/LoadTextComponentFromFileListener.java b/src/main/java/com/gyrobian/listener/LoadTextComponentFromFileListener.java index 7a4056c..7aeb641 100644 --- a/src/main/java/com/gyrobian/listener/LoadTextComponentFromFileListener.java +++ b/src/main/java/com/gyrobian/listener/LoadTextComponentFromFileListener.java @@ -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); + } } } } diff --git a/src/main/java/com/gyrobian/util/FileLoader.java b/src/main/java/com/gyrobian/util/FileLoader.java index 85bbbcb..ffdac10 100644 --- a/src/main/java/com/gyrobian/util/FileLoader.java +++ b/src/main/java/com/gyrobian/util/FileLoader.java @@ -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(); } }