简体   繁体   中英

(re-writing the text file and keep previous data)get value and write in notepad/ms-word- every time in new line of notepad file

I know how to get value from JTextField and Write it into a text file in Java language. Here is my code :

public class createfile {
    private Formatter x;

    public void openFile() {
        try {
            x = new Formatter("c:\\definition.txt");
        } catch (Exception e) {
            System.out.println("Error");
        }
    }

    private void addRecords() {
        x.format(null, jTextField3);
    }

    public void closFile() {
        x.close();
    }
}

It works properly and writes the value of jTextField3 to a file called "definition.txt". BUT If the user runs the program again, and enters new value in jTextField3, then "definition.txt" will be filled with new data ! and the previous data will lost ! I do not want to be like that ! I want to keep all the data which every time enters by user. how should I change my code ? Thank you !

You want to append to the file instead of overwriting it. The Formatter constructor which takes a file name doesn't seem up to the job. I suggest you create a FileOutputStream where you can explicitely require appending. You can pass that stream to the Formatter constructor instead of the raw file name.

x = new Formatter(new FileOutputStream("c:\\definition.txt", true));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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