Cannot write a text in a text file using FileWriter and Printwriter

1k Views Asked by At

I want to create a program more like a NotePad. When you type a text inside the JTextArea and click Save as, the program will create a text file inside the workspace with the texts typed inside the JTextArea. The problem is when I click save, the program can create a text file but the texts typed inside the textarea are not saved inside the created text file. The name of the text file is "Text". I used the getText() method to get the texts inside the TextArea.

This is the program:

import javax.swing.*;
import java.awt.event.*;
import java.awt.*;
import java.io.*;    
public class TextAreaWithMenus extends JFrame implements ActionListener {
    JTextArea area;
    JMenuBar menubar;
    JMenu option;
    JMenuItem menuitem;
    File file;
    FileWriter fwriter;
    PrintWriter pwriter;
    String order[] = {"Save as","Edit"};

    public TextAreaWithMenus() {
        setSize(new Dimension(500,500));
        setDefaultCloseOperation(this.EXIT_ON_CLOSE);
        setLocationRelativeTo(null);
        setResizable(false);
        setLayout(null);
        area = new JTextArea();
        menubar = new JMenuBar();
        option = new JMenu("File");
        for(String call : order) {
            menuitem = new JMenuItem(call);
            option.add(menuitem);
            menuitem.addActionListener(this);
        }
        this.add(menubar);
        menubar.setBounds(0,0,500,30);
        menubar.add(option);
        this.add(area);
        area.setBounds(0,30,500,470);
        area.setLineWrap(true);
        area.setWrapStyleWord(true);
        try{
            file = new File("C://Users/LunaWorkspace/TestProject/src/Text");
            fwriter = new FileWriter(file);
            pwriter = new PrintWriter(fwriter,true);
        }catch(Exception e) {}          
        setVisible(true);
    }//END OF CONSTRUCTOR

    public void save() {
        try {   
            if(!file.exists()) {
                try {
                    file.createNewFile();
                    pwriter.print(area.getText());
                    System.out.println(area.getText());
                    System.out.println("Saved complete");
                }catch(Exception ef) {
                    ef.printStackTrace();
                    System.err.print("Cannot Create");
                }                   
            }else if(file.exists()) {   
                    pwriter.print(area.getText());
                    System.out.println(area.getText());
                    System.out.println("Overwrite complete");   
            }
        } catch(Exception exp) {
            exp.printStackTrace();
            System.err.println("Cannot Save");
        }       
    }

    public void actionPerformed(ActionEvent ac) {
        String act = ac.getActionCommand();         
        if(act.equals("Save as")) {
            save();
        }else if(act.equals("Edit")) {}
    }

    public static void main (String args[]) {
        EventQueue.invokeLater(new Runnable() {
                               public void run() { new TextAreaWithMenus();} });
    }
}
3

There are 3 best solutions below

2
On BEST ANSWER

you need to call flush as the save is being buffered. This works:

public void save() {
    try {
        if (!file.exists()) {
            try {
                file.createNewFile();
                pwriter.print(area.getText());
                System.out.println(area.getText());
                System.out.println("Saved complete");

            } catch (Exception ef) {
                ef.printStackTrace();
                System.err.print("Cannot Create");
            }

        } else if (file.exists()) {
            pwriter.print(area.getText());
            System.out.println(area.getText());
            System.out.println("Overwrite complete");
        }
    } catch (Exception exp) {
        exp.printStackTrace();
        System.err.println("Cannot Save");
    } finally {
        pwriter.flush();
    }
}
0
On

You should close your Writer with pwriter.close() after finishing. Otherwise the text might not have been flushed, and nothing will be written.

0
On

Its not good practice to create the writer in the constructor and write to it repetitive in the save method. Create a new file and writing to the old stream may leading to unexpected behavior.

Open, write to and close the stream/writer in the save method.

Then it is not necessary to check if the file already exists. new FileWriter(file) will overwrite an existing file.