如何使用 PrintWriter 多次写入文本文件 [英] How to write more than once to text file using PrintWriter

查看:28
本文介绍了如何使用 PrintWriter 多次写入文本文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道如何创建 PrintWriter 并且能够从我的 gui 中获取字符串并将其打印到文本文件中.

I know how to create a PrintWriter and am able to take strings from my gui and print it to a text file.

我希望能够使用相同的程序并打印到文件中,将文本添加到文件中,而不是替换文本文件中已有的所有内容.我将如何做到这一点,以便在向文本文件中添加更多数据时,每次都将其打印在新行上?

I want to be able to take the same program and print to the file adding text to the file instead of replacing everything already in the text file. How would I make it so that when more data is added to the text file, it is printed on a new line every time?

任何示例或资源都很棒.

Any examples or resources would be awesome.

推荐答案

    try 
    {
    PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter("outfilename", true)));
    out.println("the text");
    out.close();
     } catch (IOException e) {
    }

FileWriter 构造函数的第二个参数将告诉它追加到文件中(而不是清除文件).

The second parameter to the FileWriter constructor will tell it to append to the file (as opposed to clearing the file).

推荐使用 BufferedWriter 用于昂贵的编写器(即 FileWriter),并且使用 PrintWriter 可以让您访问 println 语法,您可能已经习惯了 System.out.

Using a BufferedWriter is recommended for an expensive writer (i.e. a FileWriter), and using a PrintWriter gives you access to println syntax that you're probably used to from System.out.

但是 BufferedWriterPrintWriter 包装器并不是绝对必要的.

But the BufferedWriter and PrintWriter wrappers are not strictly necessary.

这篇关于如何使用 PrintWriter 多次写入文本文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆