[Java]PrintWriter&FileWriter 写入追加到文件

Posted profesor

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了[Java]PrintWriter&FileWriter 写入追加到文件相关的知识,希望对你有一定的参考价值。

 

//用PrintWriter写入文件
import java.io.IOException;
import java.io.PrintWriter;
public class PrintWriteDemo
{
    public static void main(String[] args) throws IOException
    {
        PrintWriter out = new PrintWriter("01.txt");
        out.print("the quick brown fox");
        out.println(" jumps over the lazy dog.");
        out.write("work is like a capricious lover whose ");
        out.write("incessant demands are resented but who is missed terribly when she is not there
");
        out.close(); //如果不关闭文件,文件停留在buffer zone, 不会写进"01.txt"中
    }
}

FileWriter只能写入文件,无法往文件中追加内容

 

 

 

//用FileWriter写入和追加文件
import java.io.IOException;
import java.io.FileWriter;
public class FileWriterDemo
{
    public static void main(String[] args) throws IOException
    {
        FileWriter out = new FileWriter("02.txt");
        //constructor中添加true,即FileWriter out = new FileWriter("02.txt", true)就是往02.txt中追加文件了
        out.write("work is like a capricious lover whose ");
        out.write("incessant demands are resented but who is missed terribly when she is not there
");
        out.write(98.7 + "
");
        out.close(); //很重要,一定记得关闭文件
    }
}

 

都别忘记 throws IOException

以上是关于[Java]PrintWriter&FileWriter 写入追加到文件的主要内容,如果未能解决你的问题,请参考以下文章

jsp\java如何编写过滤器过滤特殊字符

Java:PrintStream 和 PrintWriter 的区别

JAVA printWriter中write()和println()区别

Java IO流 之 PrintWriter

java 为PrintWriter

Java核心类库-IO-打印流(PrintStream/PrintWriter)