繁体   English   中英

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

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

我想创建一个更类似于NotePad的程序。 当您在JTextArea键入文本并单击“ 另存为”时程序将在工作区中创建一个文本文件,并在JTextArea中键入文本。 问题是当我单击“保存”时,程序可以创建一个文本文件,但是在textarea中键入的文本没有保存在创建的文本文件中。 文本文件的名称"Text" 我使用了getText()方法来获取TextArea的文本。

这是程序:

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();} });
    }
}

完成后,应使用pwriter.close()关闭Writer。 否则,文本可能不会被刷新,并且不会写入任何内容。

您需要调用flush来保存存储。 这有效:

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();
    }
}

在构造函数中创建writer并在save方法中重复写入它不是一个好习惯。 创建一个新文件并写入旧流可能会导致意外行为。

使用save方法打开,写入和关闭流/写入器。

这样就不必检查文件是否已经存在。 新的FileWriter(file)将覆盖现有文件。

暂无
暂无

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

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