写入 .txt 而不删除之前的内容

Writing in .txt without erasing the previous

我在我的代码中注意到,每当我输入一个新的输入时,我之前输入的文本就会消失并完全被新的文本取代。 如何在不删除以前文本的情况下创建新文本?

这是我的代码:

String pangalan = nameField.getText().trim();
String edad = age.getText().trim();
if(pangalan.length()!=0&&edad.length()!=0){ 
    JLabel l1 = new JLabel("Submit Success!");
    mainPanel.add(l1);
    l1.setBounds(70,115,100,100);   
    try{
        input = new Formatter(new File("jj.txt"));              
    }//try
    catch(Exception i){
        System.out.println("File not found!");
    }//catch
    input.format("%s %s",pangalan,edad);
    input.close();
}

我使用了 MadProgrammer 所说的 FileWriter(File,boolean) :) 而且效果很好 :)

这些是 java FileWriter 1.7 上的构造函数 构造函数和描述

FileWriter(File file) // Constructs a FileWriter object given a File object.
FileWriter(File file, boolean append) // Constructs a FileWriter object given a File object.
FileWriter(FileDescriptor fd) //Constructs a FileWriter object associated with a file descriptor.
FileWriter(String fileName) // Constructs a FileWriter object given a file name.
FileWriter(String fileName, boolean append) // Constructs a FileWriter object given a file name with a boolean indicating whether or not to append the data written.

有关详细信息,请参阅 API。

您必须以附加模式打开文件,这可以通过使用 FileWriter(String fileName, boolean append) 构造函数来实现。

output = new BufferedWriter(new FileWriter(my_file_name, true));

示例:

public static void main(String[] args) {
        Writer output;
        try {

            output = new BufferedWriter(new FileWriter(("E:\test.txt"), true));
            output.write("current line");
            output.close();

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

输出将是 ::

希望对您有所帮助。