package com.mstf.ui;
import java.io.*;
public class TestWriter
{
public static void main(String args[]){
//PrintWriter做過濾流+FileWriter
//doFilter1();
//2、PrintWriter做過濾流+OutputStreamWriter
//doFilter2();
//3、PrintWriter可以作為節點流
//doNode();
//4、PrintWriter可以進行橋轉換,接受一個OutputStream對象
doBridge();
}
//1、PrintWriter做過濾流+FileWriter
public static void doFilter1(){
FileWriter fw = null;
PrintWriter pw = null;
try{
//創建字符流
fw = new FileWriter("newPoem.txt");
//封裝字符流的過濾流
pw = new PrintWriter(fw);
//文件寫入
pw.println("陽關萬里道,");
pw.println("不見一人歸。");
pw.println("惟有河邊雁,");
pw.println("秋來南向飛。");
}catch(IOException e){
e.printStackTrace();
}finally{
//關閉外層流
if(pw != null){
pw.close();
}
}
}
//2、PrintWriter做過濾流+OutputStreamWriter
public static void doFilter2(){
FileOutputStream fos = null;
OutputStreamWriter osw = null;
PrintWriter pw = null;
try
{
//創建字節流
fos = new FileOutputStream("newPoem.txt");
//通過橋連接,把字節流轉變為字符流,并指定編碼格式
osw = new OutputStreamWriter(fos,"UTF-8");//寫入文件時指定編碼格式
//封裝字符流的過濾流
pw = new PrintWriter(osw);
//文件寫入
pw.println("陽關萬里道,");
pw.println("不見一人歸。");
pw.println("惟有河邊雁,");
pw.println("秋來南向飛。");
}
catch (FileNotFoundException e)
{
e.printStackTrace();
}catch(UnsupportedEncodingException e){
e.printStackTrace();
}finally{
//關閉外層流
if(pw != null){
pw.close();
}
}
}
//3、PrintWriter可以作為節點流,構造器中可以接受File對象或者文件名
public static void doNode(){
PrintWriter pw = null;
try
{
//直接創建字符節點流,并輸出
pw = new PrintWriter("newPoem.txt");
pw.println("陽關萬里道,");
pw.println("不見一人歸。");
pw.println("惟有河邊雁,");
pw.println("秋來南向飛。");
}
catch (FileNotFoundException e)
{
e.printStackTrace();
}finally{
//關閉外層流
if(pw != null){
pw.close();
}
}
}
//4、PrintWriter可以進行橋轉換,接受一個outputStream對象,不能指定編碼方式
public static void doBridge(){
FileOutputStream fos = null;
PrintWriter pw = null;
try
{
fos = new FileOutputStream("newPoem.txt");
pw = new PrintWriter(fos);
//文件寫入
pw.println("陽關萬里道,");
pw.println("不見一人歸。");
pw.println("惟有河邊雁,");
pw.println("秋來南向飛。");
}
catch (FileNotFoundException e)
{
e.printStackTrace();
}finally{
//關閉外層流
if(pw != null){
pw.close();
}
}
}
}