How to write more than once to text file using PrintWriter

一世执手 提交于 2019-12-14 03:49:13

问题


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.


回答1:


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

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

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.

But the BufferedWriter and PrintWriter wrappers are not strictly necessary.




回答2:


PrintWriter writer=new PrintWriter(new FileWriter(new File("filename"),true));
writer.println("abc");

FileWriter constructor comes with append attribute,if it is true you can append to a file.

check this




回答3:


Your PrintWriter wraps another writer, which is probably a FileWriter. When you construct that FileWriter, use the constructor that takes both a File object and an "append" flag. If you pass true as the append flag, it'll open the file in append mode, which means that new output will go at the end of the file's existing contents, rather than replacing the existing contents.



来源:https://stackoverflow.com/questions/9919178/how-to-write-more-than-once-to-text-file-using-printwriter

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!