JAVAIO編程——字符輸入輸出流

Writer

public abstract class Writer
extends Object
implements Appendable, Closeable, Flushable用於寫入字符流的抽象類。 子類必須實現的唯一方法是write(char []intint),flush()和close()。 但是,大多數子類將覆蓋此處定義的一些方法,以提供更高的效率,附加功能或兩者兼而有之。 

Appendable接口在這裏插入圖片描述
在這裏插入圖片描述
在使用Writer類進行輸出的時候,最大的操作特點在於其可以直接進行字符串處理

public void write​(String str) throws IOException
寫一個字符串。 

在後續版本才逐步有了CharSequence接口的支持,只要接受此接口的實例,就意味着可以追加String,StringBuffer,StringBuilder類的實例

private static void outpute() throws IOException {
        //定義要進行輸出的磁盤完成路徑
        File file = new File("D:" + File.separator + "test-new.txt");
        if (!file.getParentFile().exists()){
            file.getParentFile().mkdirs();
        }
        Writer fileWriter = new FileWriter(file);
        fileWriter.write("wwww.cctv.com");
        fileWriter.append("fffff");
        fileWriter.close();
    }

在這裏插入圖片描述
使用writer的最大優勢是可以對字符串進行直接處理

Reader

public abstract class Reader
extends Object
implements Readable, Closeable
用於讀取字符流的抽象類。 子類必須實現的唯一方法是read(char []intint)和close()。 但是,大多數子類將覆蓋此處定義的一些方法,以提供更高的效率,附加功能或兩者兼而有之。

在Reader類裏面並沒有提供像InputStream那樣的讀取全部內容的方法,因爲會造成內存溢出問題
在這裏插入圖片描述
範例

private static void reader() throws IOException {
        //定義要進行輸出的磁盤完成路徑
        File file = new File("D:" + File.separator + "test-new.txt");
        if (file.exists()){
            Reader fileReader = new FileReader(file);
            char[] chars = new char[1024];
            int read = fileReader.read(chars);
            System.out.println(new String(chars,0,read));
            fileReader.close();
        }
    }

Tips:對於繼承了AutoCloseable接口的子類,可以使用自動關閉流

private static void reader() {
        //定義要進行輸出的磁盤完成路徑
        File file = new File("D:" + File.separator + "test-new.txt");
        if (file.exists()){
            try (Reader fileReader = new FileReader(file);){
                char[] chars = new char[1024];
                int read = fileReader.read(chars);
                System.out.println(new String(chars,0,read));
            }catch (IOException e){
                System.out.println(e);
            }                    
        }
    }
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章