PrintWriter类

PrintWriter是一种过滤流,也是一种处理流,即能对字节流和字符流进行处理。

1.查询API后,我们发现,会有八种构造方法。即:

  • PrintWriter(File file)
    Creates a new PrintWriter, without automatic line flushing, with the specified file.
    PrintWriter(File file, String csn)
    Creates a new PrintWriter, without automatic line flushing, with the specified file and charset.
    PrintWriter(OutputStream out)
    Creates a new PrintWriter, without automatic line flushing, from an existing OutputStream.
    PrintWriter(OutputStream out, boolean autoFlush)
    Creates a new PrintWriter from an existing OutputStream.
    PrintWriter(String fileName)
    Creates a new PrintWriter, without automatic line flushing, with the specified file name.
    PrintWriter(String fileName, String csn)
    Creates a new PrintWriter, without automatic line flushing, with the specified file name and charset.
    PrintWriter(Writer out)
    Creates a new PrintWriter, without automatic line flushing.
    PrintWriter(Writer out, boolean autoFlush)
    Creates a new PrintWriter.

2.实现了三种接口。

1) Closeable接口, 所以它有pw.close()方法来实现对PrintWriter的关闭。

2) Flushable接口,所以它有pw.flush()方法来实现人为的刷新。

3) Appendable接口,所以它有pw.append(char c)方法来向此输出流中追加指定字符,等价于print().

3.方法自寻查询api

4.举例:

 1 import java.io.IOException;
 2 import java.io.PrintWriter;
 3 import java.io.FileWriter;
 4 import java.io.File;
 5 
 6 public class PrintWriterDemo {
 7 
 8     public static void main(String[] args) {
 9         PrintWriter pw = null;
10         String name = "张松伟";
11         int age = 22;
12         float score = 32.5f;
13         char sex = '';
14         try {
15             pw = new PrintWriter(new FileWriter(new File("e:\file.txt")), true);
16             pw.printf("姓名:%s;年龄:%d;性别:%c;分数:%5.2f;", name, age, sex, score);
17             pw.println();
18             pw.println("多多指教");
19             pw.write(name.toCharArray());
20         } catch (IOException e) {
21             e.printStackTrace();
22         } finally {
23             pw.close();
24         }
25     }
26 }
原文地址:https://www.cnblogs.com/laurdawn/p/5644195.html