0

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

   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

谢谢!

4

1 回答 1

2

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

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

FileWriter fw = new FileWriter(filename,true);
于 2013-06-18T17:20:54.310 回答