简体   繁体   中英

Java program not saving contents of “.txt” file

I am working on a text editor in Java as a fun side project. When I exported the project, I converted to executable JAR file to ".exe" so that I could set the text editor as the default program to open ".txt" files. I can run the ".exe" and write text and then save the file, and the file saves, but the contents of the file are not saved when I try to open the file with the text editor; however, I can open the same file with notepad, and the contents of the file show. The file saves fine in Eclipse. What do I need to fix so that the file contents are shown when I try to open them with my text editor?

Here is my code:

public class Open extends JFrame implements KeyListener {

    JPanel panel = new JPanel();
    JTextArea textArea = new JTextArea();
    JScrollPane scrollPane = new JScrollPane(textArea);

    JMenuBar menuBar = new JMenuBar();
    JMenu menu;
    JMenuItem item;
    Font systemFont;

    public Open() {

        systemFont = new Font("Times New Roman", Font.PLAIN, 20);

        textArea.setLineWrap(true);
        textArea.setWrapStyleWord(false);
        textArea.setFont(systemFont);
        panel.setLayout(new BorderLayout());
        panel.add(scrollPane);
        add(panel);

        menu = new JMenu("File");
        item = new JMenuItem("Save As");

        item.setAccelerator(KeyStroke.getKeyStroke('S', Toolkit.getDefaultToolkit ().getMenuShortcutKeyMask()));

        item.addActionListener(new ActionListener() {

            public void actionPerformed(ActionEvent ae) {

                JFileChooser JFC = new JFileChooser();
                File fileName = new File("");
                BufferedWriter writer = null;

                try {

                    int rVal = JFC.showSaveDialog(Open.this);
                    if(rVal == JFileChooser.APPROVE_OPTION) {

                        writer = new BufferedWriter(new FileWriter(JFC.getSelectedFile()));
                        writer.write(textArea.getText());

                    }
                } catch(Exception e) {
                    e.printStackTrace();
                } finally {
                    if(writer != null) {
                        try {
                            writer.close();
                        } catch(IOException e) {
                            e.printStackTrace();
                        }

                    }

                }

            }

        });

        menu.add(item);
        menuBar.add(menu);

        menu = new JMenu("Edit");
        item = new JMenuItem("Undo");

        menu.add(item);

        menu.add(item);


        menuBar.add(menu);



        add("North", menuBar);


        setLookAndFeel();       
        frameDetails("Text Editor");

    }

    public void frameDetails(String title) {

        setSize(700, 500);
        setLocationRelativeTo(null);
        setTitle(title);
        setVisible(true);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    }

    public void setLookAndFeel() {

        try {

UIManager.setLookAndFeel(javax.swing.UIManager.getSystemLookAndFeelClassName());
            SwingUtilities.updateComponentTreeUI(this);

        } catch(Exception e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) {

        Open editor = new Open();

    }

}

Here is the bit of code with the save button:

 item.addActionListener(new ActionListener() {

    public void actionPerformed(ActionEvent ae) {

        JFileChooser JFC = new JFileChooser();
        File fileName = new File("");
        BufferedWriter writer = null;

            try {

                int rVal = JFC.showSaveDialog(Open.this);
                if(rVal == JFileChooser.APPROVE_OPTION) {

                    writer = new BufferedWriter(new FileWriter(JFC.getSelectedFile()));
                    writer.write(textArea.getText());

                }
            } catch(Exception e) {
                e.printStackTrace();
            } finally {
                if(writer != null) {
                    try {
                        writer.close();
                    } catch(IOException e) {
                        e.printStackTrace();
                    }

                }

            }

        }

    });

You are never reading the text file. In order to do that, Use something like this

public void loadFile(JTextArea area, String path, String file)
{
    try
    {
        area.read(new FileReader(path + file), "Default");
    }
    catch(IOException e)
    {
        e.printStackTrace();
    }
}

Note: You don't have to have this in a method. You could just use the try - catch code

To act as a default text editor, your program needs to accept a file name as the argument to main (String[] args). It should verify the file exists, then open it, read its contents, and close it.

Also, when you save a file you should rename the former version to "name.bak" or "name~" before overwriting it with the new version, in case something goes wrong during the save.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM