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

2021-05-14 00:29

阅读:668

标签:who   quick   color   col   writer   ike   throws   文件   无法   

 

//用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

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

标签:who   quick   color   col   writer   ike   throws   文件   无法   

原文地址:https://www.cnblogs.com/profesor/p/13125861.html


评论


亲,登录后才可以留言!