[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\n");
        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\n");
        out.write(98.7 + "\n");
        out.close(); //很重要,一定记得关闭文件
    }
}

 

都别忘记 throws IOException

posted @ 2020-06-14 17:50  profesor  阅读(2859)  评论(0编辑  收藏  举报