Added some error handling.
This commit is contained in:
parent
f2e934620b
commit
724359d651
|
@ -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) {
|
||||
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);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
|
@ -33,9 +33,10 @@ 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))) {
|
||||
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) {
|
||||
|
@ -43,9 +44,5 @@ public class FileLoader {
|
|||
sb.append('\n');
|
||||
}
|
||||
return sb.toString();
|
||||
} catch (IOException e) {
|
||||
e.printStackTrace();
|
||||
return "";
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
Loading…
Reference in New Issue