From ca558084ae39e57b54517c3f0adfc2b3c8355712 Mon Sep 17 00:00:00 2001 From: Yek84ta Date: Thu, 24 Apr 2025 16:22:43 +0330 Subject: [PATCH] complete FileManager class --- editor/FileManager.java | 48 +++++++++++++++++++++++++++++++++++++++++ 1 file changed, 48 insertions(+) create mode 100644 editor/FileManager.java diff --git a/editor/FileManager.java b/editor/FileManager.java new file mode 100644 index 0000000..c05adbc --- /dev/null +++ b/editor/FileManager.java @@ -0,0 +1,48 @@ +package editor; + +import javax.swing.*; +import java.io.*; +import java.nio.file.Files; +import java.nio.file.Paths; + +public class FileManager { + public static void openFile(TextEditor textEditor, JTextArea textArea) { + JFileChooser fileChooser = new JFileChooser(); + if (fileChooser.showOpenDialog(textEditor) == JFileChooser.APPROVE_OPTION) { + File file = fileChooser.getSelectedFile(); + textEditor.currentFile = file; + try { + String content = new String(Files.readAllBytes(Paths.get(file.getPath()))); + textArea.setText(content); + } catch (IOException e) { + JOptionPane.showMessageDialog(textEditor, "Sorry, we can't open this file. Please check the format and try again.", "Error", JOptionPane.ERROR_MESSAGE); + } + } + } + + public static void saveFile(TextEditor textEditor, JTextArea textArea) { + if (textEditor.currentFile == null) { + JFileChooser fileChooser = new JFileChooser(); + if (fileChooser.showSaveDialog(textEditor) == JFileChooser.APPROVE_OPTION) { + File file = fileChooser.getSelectedFile(); + textEditor.currentFile = file; + try (FileWriter writer = new FileWriter(file)) { + writer.write(textArea.getText()); + } catch (IOException e) { + JOptionPane.showMessageDialog(textEditor, "Failed to save the file. Please try again.", "Error", JOptionPane.ERROR_MESSAGE); + } + } + } else { + try (FileWriter writer = new FileWriter(textEditor.currentFile)) { + writer.write(textArea.getText()); + } catch (IOException e) { + JOptionPane.showMessageDialog(textEditor, "Failed to save the file. Please try again.", "Error", JOptionPane.ERROR_MESSAGE); + } + } + } + + public static void newFile(TextEditor textEditor, JTextArea textArea) { + textEditor.currentFile = null; + textArea.setText(""); + } +} \ No newline at end of file