且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何将数据添加到文本文件而不覆盖Java中的内容

更新时间:2023-12-03 08:40:58

建议使用BufferedWriterFileWriter链,关键点是FileWriter将在使用时将字符串附加到当前文件通过在最后一个参数中添加true这样的

It is advised to use chain of BufferedWriter and FileWriter, and the key point is FileWriter will append String to current file when use the one of its constructor that lets appaneding by adding true to last paramter like

new FileWriter("login.txt", true)        

以及当我们用BufferedWriter对象将其包围时,如果要多次写入文件,则效率更高,因此它会将字符串缓冲为大块并将大块写入文件中,并且很明显您可以节省大量时间来写入文件

and when we surrounding it with BufferedWriter object in order to be more efficient if you are going to write in the file number of time, so it buffers the string in big chunk and write the big chunk into a file and clearly you can save a lot of time for writing into a file

注意:可能不使用BuffredWriter,但建议使用此方法,因为它具有更好的性能和缓冲大字符串并写入一次的能力

Note :It is possible not to use BuffredWriter ,but it is advised because of better performance and ability to buffer the big chunk of Strings and write them once

只需更改您的

PrintWriter out = new PrintWriter("login.txt"); 

PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter("login.txt", true)));

示例:

try(PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter("login.txt", true)));) {
    String data = "This content will append to the end of the file";
    File file = new File("login.txt");
    out.println(data);
} catch(IOException e) {
}

可以不使用BufferedWriter来解决此问题,但是性能会降低,就像我提到的那样.

It is possible to solve this issue without using BufferedWriter, yet the performance will be low as I mentioned.

示例:

try (PrintWriter out = new PrintWriter(new FileWriter("login.txt", true));) {
    String data = "This content will append to the end of the file";
    File file = new File("login.txt");
    out.println(data);
} catch (IOException e) {
}