没有从应用程序写入文件

时间:2013-06-18 17:16:49

标签: java

这是我的代码,代码下面是我遇到的问题:

   import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JTextArea;
import javax.swing.JTextField;

import java.awt.TextField;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.FileWriter;
import java.io.IOException;



public class Write extends JFrame {
    JTextArea text;
    public  Write(){
        this.setTitle("Lista Carti!");
        setSize(400, 200);
        setResizable(false);
        setLocation(370, 150);
        setLayout(null);

        JLabel lbltitlu = new JLabel("Titlu");
        lbltitlu.setBounds(85, 5, 120, 25);
        this.add(lbltitlu);

        JTextArea text = new JTextArea();
        text.setSize(199,199);
        text.setBounds(85, 65, 120, 25);
        add(text);

        JButton btn = new JButton("Adauga text");
        btn.setSize(99,99);
        btn.setBounds(125, 125, 120, 25);
        add(btn);

         ActionListener listenerbtn = new ActionListener() {
                @Override
                public void actionPerformed(ActionEvent arg0) {
                    // TODO auto- generated method
                    String actionbtn = arg0.getActionCommand();

                    if (actionbtn.equals("Adauga")) {
                        Adauga();
                    }
                }
            };
            btn.addActionListener(listenerbtn);
    }
        public void Adauga(){
        String filename = "test.txt";

        FileWriter writer = null;
        try {
          writer = new FileWriter(filename);
          text.write(writer);
        } catch (IOException exception) {
          System.err.println("Save oops");
        } finally {
          if (writer != null) {
            try {
              writer.close();
            } catch (IOException exception) {
              System.err.println("Error closing writer");
              exception.printStackTrace();
            }
          }
        }


    }


}

This is my code to write into a file,but it does autowrite when i hover the button and when i reenter the application it won't write again in the same file, any help please? ----- Old request

新请求 - > 我已经编辑了我的代码,实现了actionListener但它没有输入任何东西到外部文件中。可以请一些人告诉我为什么或我在哪里犯了我的错误,顺便说一下,我是一个菜鸟程序员? :d

谢谢!

1 个答案:

答案 0 :(得分:2)

要附加到文件,请使用构造函数File(filename,append)

  

在给定File对象的情况下构造FileWriter对象。如果第二个参数为true,则字节将写入文件的末尾而不是开头。

FileWriter fw = new FileWriter(filename,true);