PrintWriter vs FileWriter in Java

2019-01-08 06:27发布

Are PrintWriter and FileWriter in Java the same and no matter which one to use? So far I have used both because their results are the same. Is there some special cases where it makes sense to prefer one over the other?

public static void main(String[] args) {

    File fpw = new File("printwriter.txt");
    File fwp = new File("filewriter.txt");
    try {
        PrintWriter pw = new PrintWriter(fpw);
        FileWriter fw = new FileWriter(fwp);
        pw.write("printwriter text\r\n");
        fw.write("filewriter text\r\n");
        pw.close();
        fw.close();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

}

7条回答
仙女界的扛把子
2楼-- · 2019-01-08 07:31

just to provide more info related to FLUSH and Close menthod related to FileOutputStream

flush() ---just makes sure that any buffered data is written to disk flushed compltely and ready to write again to the stream (or writer) afterwards.

close() ----flushes the data and closes any file handles, sockets or whatever.Now connection has been lost and you can't write anything to outputStream.

查看更多
登录 后发表回答