简体   繁体   English

无法使用FileWriter和Printwriter在文本文件中写入文本

[英]Cannot write a text in a text file using FileWriter and Printwriter

I want to create a program more like a NotePad . 我想创建一个更类似于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 . 当您在JTextArea键入文本并单击“ 另存为”时程序将在工作区中创建一个文本文件,并在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. 问题是当我单击“保存”时,程序可以创建一个文本文件,但是在textarea中键入的文本没有保存在创建的文本文件中。 The name of the text file is "Text" . 文本文件的名称"Text" I used the getText() method to get the texts inside the TextArea . 我使用了getText()方法来获取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();} });
    }
}

You should close your Writer with pwriter.close() after finishing. 完成后,应使用pwriter.close()关闭Writer。 Otherwise the text might not have been flushed, and nothing will be written. 否则,文本可能不会被刷新,并且不会写入任何内容。

you need to call flush as the save is being buffered. 您需要调用flush来保存存储。 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();
    }
}

Its not good practice to create the writer in the constructor and write to it repetitive in the save method. 在构造函数中创建writer并在save方法中重复写入它不是一个好习惯。 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. 使用save方法打开,写入和关闭流/写入器。

Then it is not necessary to check if the file already exists. 这样就不必检查文件是否已经存在。 new FileWriter(file) will overwrite an existing file. 新的FileWriter(file)将覆盖现有文件。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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