PrintWriter做过滤流+FileWriter案例分析

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();
}
}
}
}

点赞