天天看點

秒懂字元輸出流:Writer | 帶你學《Java語言進階特性》之五十五

上一篇:有出有入:使用位元組輸入流 | 帶你學《Java語言進階特性》之五十四

在前幾節中我們了解了位元組輸出流和位元組輸入流的相關定義和使用方法,但在程式運作過程中不難發現往往字元級别的操作更為常見,是以Java在JDK1.1時推出了字元流,本節将介紹字元輸出流Writer。

【本節目标】

通過閱讀本節内容,你将了解字元輸出流Writer類的基本定義和繼承關系圖,了解其内的各種方法的功能,并學會使用字元輸出流實作資料寫入功能。

Writer字元輸出流

使用OutputStream位元組輸出流進行資料輸出的時候使用的都是位元組類型的資料,而很多情況下字元串的輸出是比較友善的,是以對于java.io包而言,在JDK1.1的時候又推出了字元輸出流:Writer,這個類的定義如下:

public abstract class Writer extends Object implements Appendable, Closeable, Flushable           
秒懂字元輸出流:Writer | 帶你學《Java語言進階特性》之五十五

Writer

在Writer類裡面提供有許多的輸出操作方法,重點關注兩個:

  • 輸出字元數組:public void write(char[] cbuf) throws IOException;
  • 輸出字元串:public void write(String str) throws IOException;

範例:使用Writer類輸出

import java.io.File;
import java.io.FileWriter;
public class JavaAPIDemo {
    public static void main(String[] args) throws Exception {
        File file = new File("D:"+ File.separator + "hello" + File.separator + "mldn.txt");
        if (!file.getParentFile().exists()) {
            file.getParentFile().mkdirs();   //父目錄必須存在
        }
        //  Writer out =new FileWriter(file, true);//内容追加
        Writer out = new FileWriter(file);   //内容覆寫
        String str = "www.mldn.cn";
        out.write(str);
        out.close();
    }
}           
import java.io.File;
import java.io.FileWriter;
public class JavaAPIDemo {
    public static void main(String[] args) throws Exception {
        File file = new File("D:"+ File.separator + "hello" + File.separator + "mldn.txt");
        if (!file.getParentFile().exists()) {
            file.getParentFile().mkdirs();   //父目錄必須存在
        }
        Writer out = new FileWriter(file);   //内容覆寫
        String str = "www.mldn.cn\r\n";
        out.write(str);
        out.append("中國人民萬歲。");   //追加輸出内容
        out.close();
    }
}           

使用Writer輸出的最大優勢在于可以直接利用字元串完成。Writer是字元流,字元處理的優勢在于中文資料上。

想學習更多的Java的課程嗎?從小白到大神,從入門到精通,更多精彩不容錯過!免費為您提供更多的學習資源。

本内容視訊來源于

阿裡雲大學 下一篇:掌握字元輸入流:Reader | 帶你學《Java語言進階特性》之五十六 更多Java面向對象程式設計文章檢視此處