簡體   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