Java IO流PrintWriter

构造函数参数

1,字符串路

2,File对象

3,字节输出流

4,字符输出流

PrintWriter(File file)
使用指定文件创建不具有自动行刷新的新 PrintWriter

PrintWriter(File file, String csn)
创建具有指定文件和字符集且不带自动刷行新的新 PrintWriter

PrintWriter(OutputStream out)
根据现有的 OutputStream 创建不带自动行刷新的新 PrintWriter

PrintWriter(OutputStream out, boolean autoFlush)
通过现有的 OutputStream 创建新的 PrintWriter

PrintWriter(String fileName)
创建具有指定文件名称且不带自动行刷新的新 PrintWriter

PrintWriter(String fileName, String csn)
创建具有指定文件名称和字符集且不带自动行刷新的新 PrintWriter

PrintWriter(Writer out)
创建不带自动行刷新的新 PrintWriter

PrintWriter(Writer out, boolean autoFlush)
创建新 PrintWriter

 
import java.io.BufferedReader;

import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;

public class PrintWriterDemo {
   public static void main(String[] args) throws IOException {
      BufferedReader bufr = new BufferedReader(new InputStreamReader(System.in));
      PrintWriter out = new PrintWriter(new FileWriter("C:\\print.txt"), true);// true表示自动刷新
      // PrintWriter out = new PrintWriter(System.in, true);
      String line = null;
      while ((line = bufr.readLine()) != null) {
         if ("over".equals(line))
            break;
         out.println(line);
         // out.flush();
      }
      bufr.close();
      out.close();
   }
}

//从控制台输入数据,保存到指定文件中
public static void writeFile(String path) {
   try {
      BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
      PrintWriter pw = new PrintWriter(new FileWriter(path), true);
      String line = null;
      System.out.println("请输入要保存到文件的数据,键入\"quit\"终止输入");
      while (!"quit".equalsIgnoreCase((line = br.readLine()))) {
        pw.println("【"+ new SimpleDateFormat("yyyy-MM-dd hh:mm;ss").format(new Date()) + "】" + line);
      }
      pw.close();
   } catch (IOException e) {
      e.printStackTrace();
   }
}