PrintWriter没有写入文件,尝试添加flush()和close()Java

时间:2012-12-10 00:19:53

标签: java file-io printwriter

试图写入文件。我的研究,确保冲洗和关闭。我想也许它正在阅读消息框空白并且什么都没写,但是做了一个System.out.println以确保它正确读取,它就是。所以现在不确定。

原始代码:

import java.awt.*;
import java.awt.event.*;
import java.applet.*;
import java.io.*;

public class Form extends Applet implements ActionListener{
private TextField first = new TextField("First Name",12);
private TextField middle = new TextField("I",1);
private TextField last = new TextField("Last Name",15);
private TextField address = new TextField("Address",25);
private TextField city = new TextField("City",20);
private TextField state = new TextField("State",2);
private TextField zip = new TextField("Postal Code",10);
private Button submit =new Button("Submit");
private Button reset = new Button("Reset");
private Button save = new Button("Save");
private Button enlarge = new Button("Enlarge");
private TextArea message = new TextArea();


public void init()
{
    GridBagLayout gbl = new GridBagLayout();
    setLayout(gbl);
    GridBagConstraints c = new GridBagConstraints();
    c.anchor = GridBagConstraints.WEST;
    c.weightx=1.0;
    c.weighty=1.0;
    c.fill=GridBagConstraints.HORIZONTAL;
    c.insets=new Insets(5,5,5,5);
    gbl.setConstraints(first,c); add(first);
    c.fill=GridBagConstraints.NONE;
    gbl.setConstraints(middle,c); add(middle);
    c.fill=GridBagConstraints.HORIZONTAL;
    gbl.setConstraints(last,c); add(last);
    c.gridy=1;
    gbl.setConstraints(address,c); add(address);
    c.gridy=2;
    gbl.setConstraints(city,c); add(city);
    c.fill=GridBagConstraints.NONE;
    gbl.setConstraints(state,c); add(state);
    c.gridy=3;
    gbl.setConstraints(zip,c); add(zip);
    c.gridy=4;
    c.anchor = GridBagConstraints.CENTER;
    gbl.setConstraints(submit,c);add(submit);
    gbl.setConstraints(reset,c); add(reset);
    c.gridy=5;
    c.anchor = GridBagConstraints.CENTER;
    gbl.setConstraints(save, c); add(save);
    gbl.setConstraints(enlarge, c); add(enlarge);
    c.gridy=6;
    c.gridwidth=3;
    c.fill=GridBagConstraints.BOTH;
    gbl.setConstraints(message,c);add(message);
    submit.addActionListener(this);
    reset.addActionListener(this);
    enlarge.addActionListener(this);
    save.addActionListener(this);
}
public void actionPerformed(ActionEvent event)
{

    String initial = middle.getText();
    String a=message.getText();
    if (initial != null)
        initial +=". ";
    Object source = event.getSource();
    if (source == submit)
    {

        message.setText(first.getText()+ ' ' +initial+last.getText());
        message.append('\n'+address.getText());
        message.append('\n'+city.getText()+", " +state.getText());
        message.append(' ' +zip.getText());
        message.append("\n\nYour message:\n"+a);
    }
    else if (source == reset)
    {
        message.setText("");
        first.setText("");
        middle.setText("");
        last.setText("");
        address.setText("");
        city.setText("");
        state.setText("");
        zip.setText("");

    }
    else if (source == enlarge)

    {
        message.setFont(new Font("Serif", Font.PLAIN, 14));
        message.setForeground(Color.BLUE);
        message.setText(a);
    }
    else if (source == save)
    {
        try{


        File file=new File("savedMessage.txt");
        PrintWriter pw = new PrintWriter(file);
                pw.println(message.getText());
                //message.setText("Print was successful")
                pw.flush();
                pw.close();
                System.out.println(message.getText());
        }
        catch (FileNotFoundException e) {
            e.printStackTrace();
            System.err.println("Error: " + e.getMessage());

        } catch (IOException e) {
            e.printStackTrace();
            System.err.println("Error: " + e.getMessage());
        }

    }

}

}

以下是用于解决问题的代码:

    else if (source == save)
    {
        try{
            f = new File("savedMessage.txt");
            bw = new BufferedWriter(new FileWriter(f,true));
            bw.write(message.getText());
            if(f.canWrite()){
            System.out.println("Success");
            }
            }

        catch (FileNotFoundException e) {
            e.printStackTrace();
            System.err.println("Error: " + e.getMessage());

        } catch (IOException e) {
            e.printStackTrace();
            System.err.println("Error: " + e.getMessage());
        }
    finally{

            try {
                bw.close();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }

2 个答案:

答案 0 :(得分:2)

PrintWriter吞下例外情况。见Javadoc。您需要致电checkError()。更好的是,使用BufferedWriter,它不会吞下它们。除非您的applet已签名,否则您可能会遇到苹果沙箱权限问题。

答案 1 :(得分:0)

First Tipp:关闭文件! 在catch ioexception下你添加一个finally块

    File file = null;
    try {
       file = new File("filename.txt");
    } catch (IOException ex) {

    } finally {
       try {
            file.close();
        } catch (IoException ex2) { }

    }

进一步检查文件是否可写

if (!file.canWrite()) {
// forget it, cannit write
 }