java printwriter实例_PrintWriter做过滤流+FileWriter案例分析
package com.mstf.ui;
import java.io.*;
public class TestWriter
{
public static void main(String args[]){
//PrintWriter做過(guò)濾流+FileWriter
//doFilter1();
//2、PrintWriter做過(guò)濾流+OutputStreamWriter
//doFilter2();
//3、PrintWriter可以作為節(jié)點(diǎn)流
//doNode();
//4、PrintWriter可以進(jìn)行橋轉(zhuǎn)換,接受一個(gè)OutputStream對(duì)象
doBridge();
}
//1、PrintWriter做過(guò)濾流+FileWriter
public static void doFilter1(){
FileWriter fw = null;
PrintWriter pw = null;
try{
//創(chuàng)建字符流
fw = new FileWriter("newPoem.txt");
//封裝字符流的過(guò)濾流
pw = new PrintWriter(fw);
//文件寫入
pw.println("陽(yáng)關(guān)萬(wàn)里道,");
pw.println("不見一人歸。");
pw.println("惟有河邊雁,");
pw.println("秋來(lái)南向飛。");
}catch(IOException e){
e.printStackTrace();
}finally{
//關(guān)閉外層流
if(pw != null){
pw.close();
}
}
}
//2、PrintWriter做過(guò)濾流+OutputStreamWriter
public static void doFilter2(){
FileOutputStream fos = null;
OutputStreamWriter osw = null;
PrintWriter pw = null;
try
{
//創(chuàng)建字節(jié)流
fos = new FileOutputStream("newPoem.txt");
//通過(guò)橋連接,把字節(jié)流轉(zhuǎn)變?yōu)樽址?#xff0c;并指定編碼格式
osw = new OutputStreamWriter(fos,"UTF-8");//寫入文件時(shí)指定編碼格式
//封裝字符流的過(guò)濾流
pw = new PrintWriter(osw);
//文件寫入
pw.println("陽(yáng)關(guān)萬(wàn)里道,");
pw.println("不見一人歸。");
pw.println("惟有河邊雁,");
pw.println("秋來(lái)南向飛。");
}
catch (FileNotFoundException e)
{
e.printStackTrace();
}catch(UnsupportedEncodingException e){
e.printStackTrace();
}finally{
//關(guān)閉外層流
if(pw != null){
pw.close();
}
}
}
//3、PrintWriter可以作為節(jié)點(diǎn)流,構(gòu)造器中可以接受File對(duì)象或者文件名
public static void doNode(){
PrintWriter pw = null;
try
{
//直接創(chuàng)建字符節(jié)點(diǎn)流,并輸出
pw = new PrintWriter("newPoem.txt");
pw.println("陽(yáng)關(guān)萬(wàn)里道,");
pw.println("不見一人歸。");
pw.println("惟有河邊雁,");
pw.println("秋來(lái)南向飛。");
}
catch (FileNotFoundException e)
{
e.printStackTrace();
}finally{
//關(guān)閉外層流
if(pw != null){
pw.close();
}
}
}
//4、PrintWriter可以進(jìn)行橋轉(zhuǎn)換,接受一個(gè)outputStream對(duì)象,不能指定編碼方式
public static void doBridge(){
FileOutputStream fos = null;
PrintWriter pw = null;
try
{
fos = new FileOutputStream("newPoem.txt");
pw = new PrintWriter(fos);
//文件寫入
pw.println("陽(yáng)關(guān)萬(wàn)里道,");
pw.println("不見一人歸。");
pw.println("惟有河邊雁,");
pw.println("秋來(lái)南向飛。");
}
catch (FileNotFoundException e)
{
e.printStackTrace();
}finally{
//關(guān)閉外層流
if(pw != null){
pw.close();
}
}
}
}
總結(jié)
以上是生活随笔為你收集整理的java printwriter实例_PrintWriter做过滤流+FileWriter案例分析的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: 3dmax如何拆分模型_3dmax制作装
- 下一篇: iphone短信尚未送达_第五期:从苹果