Demo.java:
package cn.xxx.demo;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
/*
* 列印流
* PrintStream 列印位元組流
* PrintWriter 列印字元流(較常用)
* 列印流的特點:
* 1. 此流不負責資料源,隻負責資料目的
* 2. 為其他輸出流,添加功能
* 3. 永遠不會抛出IOException
* 但是,可能抛出别的異常
*
* 兩個列印流的方法,完全一緻
* 構造方法,就是列印流的輸出目的端
* PrintStream
* 構造方法,接收File類型,接收字元串檔案名,接收位元組輸出流OutputStream
* PrintWriter
* 構造方法,接收File類型,接收字元串檔案名,接收位元組輸出流OutputStream, 接收字元輸出流Writer
*
*/
public class Demo {
public static void main(String[] args) throws IOException {
function();
}
/*
* 列印流,可以開啟自動flush重新整理功能
* 滿足2個條件:
* 1. 輸出的資料目的必須是流對象。 (用File檔案對象和String檔案名構造PrintWriter不能開啟自動重新整理功能,因為第二個參數表示編碼表)
* OutputStream(位元組流) Writer(字元流)
* 可以将File檔案或String檔案名包裝成流對象,然後再構造PrintWriter來開啟自動重新整理功能。
* 2. 必須調用println,printf,format三個方法中的一個,啟用自動重新整理
*/
public static void function_1()throws IOException{
FileOutputStream fos = new FileOutputStream("c:\\5.txt");
PrintWriter pw = new PrintWriter(fos,true); // true 表示開啟自動flush重新整理功能
pw.println("i");
pw.println("love");
pw.println("java");
pw.close();
}
/*
* 列印流,寫入資料
* 方法print println int原樣輸出,不走碼表。 可以列印char[]數組(String的本質就是char[]);其他類型數組,隻會列印位址。
* write(int a)方法 寫入一個字元,走碼表。 還可以寫String、char[]數組。
*/
public static void function() throws FileNotFoundException{
PrintWriter pw = new PrintWriter("c:\\1.txt"); // 構造函數傳String
//PrintWriter pw = new PrintWriter(new File("c:\\2.txt")); // 構造函數傳檔案File
//PrintWriter pw = new PrintWriter(new FileWriter("c:\\3.txt")); // 構造函數傳字元流FileWriter
//PrintWriter pw = new PrintWriter(new FileOutputStream("c:\\4.txt")); // 構造函數傳位元組流FileOutputStream
pw.println(100); // println 自動加換行。 原樣輸出,不走碼表。
pw.write(100); // write(int)方法寫入一個字元,走碼表。 還可以寫String、char[]數組。
pw.close();
}
}