天天看點

java常用IO流操作一、概述二、File類三、InputStream及其子類四、OutputStream及其子類五、Reader及其子類六、Writer及其子類

文章目錄

  • 一、概述
    • 1. 流的分類
    • 2. 常用流的繼承關系
  • 二、File類
    • 1. 構造方法
    • 2. 執行個體方法
    • 3. 靜态方法
    • 4. 一些例子
  • 三、InputStream及其子類
    • 1. InputStream
    • 2. FileInputStream
    • 3. BufferedInputStream
    • 4. DataInputStream
    • 5. ObjectInputStream
  • 四、OutputStream及其子類
    • 1. OutputStream
    • 2. FileOutputStream
    • 3. BufferedOutputStream
    • 4. DataOutputStream
    • 5. ObjectOutputStream
    • 6. PrintStream
  • 五、Reader及其子類
    • 1. Reader
    • 2. InputStreamReader
    • 3. FileReader
    • 4. BufferedReader
  • 六、Writer及其子類
    • 1. Writer
    • 2. OutputStreamWriter
    • 3. FileWriter
    • 4. BufferedWriter
    • 5. PrintWriter

一、概述

1. 流的分類

IO

:Java對資料的操作是通過流的方式,IO流用來處理裝置之間的資料傳輸,上傳檔案和下載下傳檔案,Java用于操作流的對象都在IO包中。可以分為:

  • 輸入/輸出流:是以目前程式為中心,程式從外面讀資料是輸入流,程式把資料儲存到外面是輸出流
  • 位元組流/字元流:如果是以位元組為機關處理流中的資料就是位元組流,如果是以字元為機關處理流中的資料就是字元流
  • 節點流/處理流:如果直接操作資料源就是節點流;處理流不直接操作資料源,是對其他流的包裝

java.io

包中位元組流都是以

Stream

單詞結尾,字元流以

Reader/Writer

結尾

2. 常用流的繼承關系

  • 位元組輸入流:
    java常用IO流操作一、概述二、File類三、InputStream及其子類四、OutputStream及其子類五、Reader及其子類六、Writer及其子類
  • 位元組輸出流:
    java常用IO流操作一、概述二、File類三、InputStream及其子類四、OutputStream及其子類五、Reader及其子類六、Writer及其子類
  • 字元輸入流:
    java常用IO流操作一、概述二、File類三、InputStream及其子類四、OutputStream及其子類五、Reader及其子類六、Writer及其子類
  • 字元輸出流:
    java常用IO流操作一、概述二、File類三、InputStream及其子類四、OutputStream及其子類五、Reader及其子類六、Writer及其子類

二、File類

Java

檔案類以抽象的方式代表檔案名和目錄路徑名。該類主要用于檔案和目錄的建立、檔案的查找和檔案的删除等。

File

對象代表磁盤中實際存在的檔案或目錄。

1. 構造方法

File(File parent, String child) 通過給定的 父抽象路徑名 和 子路徑名字元串 建立一個新的

File

執行個體
File(String pathname) 通過将 給定路徑名字元串 轉換成抽象路徑名來建立一個新 File 執行個體
File(String parent, String child) 根據 parent 路徑名字元串和 child 路徑名字元串建立一個新 File 執行個體。

2. 執行個體方法

建立

File

對象成功後,可以使用以下清單中的執行個體方法操作檔案(标注了的比較常用):

執行個體方法 傳回值類型 說明

getName()

String 傳回此File表示的檔案或目錄的名稱。
getParent() String 傳回父路徑名字元串,如果不存在,則傳回null。
getParentFile() File 傳回父路徑名File,如果不存在,則傳回null
getPath() String 将此路徑名轉換為路徑名字元串。
isAbsolute() boolean 測試這個抽象路徑名是否是絕對的。
getAbsoluteFile() File 傳回絕對路徑的File。
getAbsolutePath() String 傳回絕對路徑的字元串。
canExecute()/canRead()/canWrite() boolean 測試應用程式是否可以執行/讀取/修改此抽象路徑名表示的檔案。

isDirectory()

boolean 測試此抽象路徑名表示的檔案是否為目錄。

isFile()

boolean 測試此抽象路徑名表示的檔案是否為普通檔案。

createNewFile()

boolean 當檔案不存在時,建立一個新的空檔案。

mkdir()

boolean 建立目錄,不包括父目錄。
mkdirs() boolean 建立目錄,包括父目錄。
list() String[] 傳回一個字元串數組,命名由此抽象路徑名表示的目錄中的檔案和目錄。

list(FilenameFilter filter)

String[] 傳回一個字元串數組,傳回目錄中滿足過濾器的檔案和目錄。
listFiles() File[] 傳回一個抽象路徑名數組,表示由該抽象路徑名表示的目錄中的檔案。

listFiles(FilenameFilter filter)

File[] 傳回一個抽象路徑名數組,表示由該抽象路徑名表示的目錄中的檔案。
lastModified() long 傳回此抽象路徑名表示的檔案上次修改的時間。
length() long 傳回由此抽象路徑名表示的檔案的長度。
renameTo(File dest) boolean 重命名由此抽象路徑名表示的檔案。
toPath() Path 傳回從此抽象路徑構造的java.nio.file.Path對象。

delete()

boolean 删除由此抽象路徑名表示的檔案或目錄。
deleteOnExit() void 請求在虛拟機終止時删除由此抽象路徑名表示的檔案或目錄。

exists()

boolean 測試此抽象路徑名表示的檔案或目錄是否存在。
setLastModified(long time) boolean 設定由此抽象路徑名所指定的檔案或目錄的最後一次修改時間。
setReadOnly() boolean 标記此抽象路徑名指定的檔案或目錄,以便隻可對其進行讀操作。
compareTo(File pathname) int 按字母順序比較兩個抽象路徑名。
compareTo(Object o) int 按字母順序比較抽象路徑名與給定對象。
equals(Object obj) boolean 測試此抽象路徑名與給定對象的相等性。
toString() String 傳回此抽象路徑名的路徑名字元串。

3. 靜态方法

靜态方法 傳回值類型 說明
createTempFile(String prefix, String suffix, File directory) File 在指定目錄中建立一個新的空檔案,使用給定的字首和字尾字元串生成其名稱。
createTempFile(String prefix, String suffix) File 在預設臨時檔案目錄中建立一個空檔案,使用給定字首和字尾生成其名稱。

4. 一些例子

  1. 輸出指定檔案夾下所有的

    .txt

    檔案(包括子檔案夾)
    //顯示檔案夾的内容,包含子檔案夾的内容
    private static void listSub(String folder) {
        File file = new File(folder);
    
        File[] files = file.listFiles();
        if (files != null) {
            for (File f : files) {
                //如果f是檔案夾, 把f這個子檔案夾的内容也顯示出來
                if (f.isDirectory()) {
                	//如果是子目錄,則遞歸調用子目錄
                    listSub(f.getAbsolutePath());
                } else if (f.getName().endsWith(".txt")) {
                	//如果是檔案,且檔案名以.txt結尾,則輸出
                    System.out.println(f.getAbsolutePath());
                }
            }
        }
    }
               

三、InputStream及其子類

1. InputStream

InputStream

是位元組輸入流基類,抽象類是表示位元組輸入流的所有類的超類。

方法 說明
int available() 傳回從此輸入流中可以讀取(或跳過)的剩餘位元組數的估計值
abstract int read() 從輸入流中讀取資料的下一個位元組,傳回讀到的下一個位元組,如果讀不到則傳回 -1

int read(byte[] b)

從輸入流中讀取一定數量的位元組,并将其存儲在緩沖區數組 b中,傳回讀到的位元組個數,讀到末尾傳回 -1
int read(byte[] b, int off, int len) 将輸入流中最多 len 個資料位元組讀入 byte 數組,傳回讀到的位元組個數,讀到末尾傳回 -1
long skip(long n) 跳過和丢棄此輸入流中資料的 n個位元組

void close()

關閉此輸入流并釋放與該流關聯的所有系統資源
在讀取檔案時,在檔案中有一個遊标的存在,剛剛打開檔案時遊标指向最前面,每次讀取檔案内容後,遊标都會向後移動

2. FileInputStream

FileInputStream

是位元組檔案輸入流,從檔案系統中的某個檔案中獲得輸入位元組,用于讀取諸如圖像資料之類的原始位元組流。

  • 構造方法:
    構造方法 說明

    FileInputStream(File file)

    通過打開與實際檔案的連接配接建立一個 FileInputStream ,該檔案由檔案系統中的 File對象 file命名。

    FileInputStream(String name)

    通過打開與實際檔案的連接配接來建立一個 FileInputStream ,該檔案由檔案系統中的路徑名 name命名。
  • 執行個體方法:

    FileInputStream

    覆寫和重寫了父類的的常用方法。
  • 自動釋放資源:
    public static void main(String[] args) throws IOException {
        //從JDK7開始,可以自動關閉流,也可以在finally語句塊中進行關閉
        //try後面使用一對小括弧,這是try資源塊,try資源塊可以自動釋放
        try (
                FileInputStream fis = new FileInputStream("D:\\course\\03-JavaSE\\file\\abcd.txt");
        ) {
            int cc = -1;
            while ((cc = fis.read()) != -1) {
                System.out.print((char) cc);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
               
  • 将檔案中讀取的位元組存儲到位元組數組中:
    //将檔案中讀取的位元組存儲到位元組數組中
    public static void main(String[] args) throws IOException {
        //1)建立流通道
        FileInputStream fis = new FileInputStream("D:\\course\\03-JavaSE\\file\\abc.txt");
        //檔案内容:abcdefhehe
    
        //先定義一個位元組數組, 在實際應用中,位元組數組的大小一般是1024的偶數倍,這裡選擇8倍
        byte[] bytes = new byte[4];
    
        //通過fis位元組流讀取檔案中的位元組,把讀取到的位元組存儲到位元組數組中, 傳回讀取的位元組數
        int len = fis.read(bytes);
    
        while (len != -1) {
            //處理從檔案中讀到的len個位元組, 把bytes數組中前len個位元組轉換為字元串
            System.out.println(new String(bytes, 0, len));
    
            //繼續從檔案中讀取,還儲存到bytes數組中
            len = fis.read(bytes);
        }
        
        //上面循環的拆解版,容易看到執行過程
       /* System.out.println(Arrays.toString(bytes));   //[97, 98, 99, 100]
        System.out.println(len);        //4
    
        len = fis.read(bytes);
        System.out.println(Arrays.toString(bytes));     //[101, 102, 104, 101]
        System.out.println(len);        //4
    
        len = fis.read(bytes);
        System.out.println(Arrays.toString(bytes));     //[104, 101, 104, 101]
        System.out.println(len);        //2
    
        len = fis.read(bytes);
        System.out.println(Arrays.toString(bytes));     //[104, 101, 104, 101]
        System.out.println(len);        //-1*/
        fis.close();
    }
               

3. BufferedInputStream

BufferedInputStream

是位元組緩沖輸入流,提高了讀取效率

  • 構造方法:
    構造方法 說明
    ufferedInputStream(InputStream in) 建立一個 BufferedInputStream并儲存其參數,即輸入流in,以便将來使用。
    ufferedInputStream(InputStream in, int size) 建立具有指定緩沖區大小的 BufferedInputStream并儲存其參數,即輸入流in以便将來使用
  • 常用方法同

    InputStream

public static void main(String[] args) throws IOException {
    //1)先建立位元組流
    FileInputStream fis = new FileInputStream("D:\\course\\03-JavaSE\\file\\abc.txt");
    //再建立緩沖流,對位元組流進行緩沖
    BufferedInputStream bis = new BufferedInputStream(fis);

    byte[] bs = new byte[20];
    int len = 0;
    while ((len = bis.read(bs)) != -1) {
        System.out.print(new String(bs, 0, len));
    }
    // 關閉流
    bis.close();
}
           

4. DataInputStream

DataInputStream

用于讀取在檔案中儲存的帶有資料格式(基本類型和String)的資料

注意:

DataOutputStream

DataInputStream

配合使用,而且二者 讀寫的順序要一樣

  • 構造方法:
    構造方法 說明
    DataInputStream(InputStream in) 通過輸入流InputStream來建立一個 DataInputStream。
  • 常用方法,除了實作父類的方法外,還有如下方法:
    方法 說明
    boolean readBoolean() 讀取bollean類型的值
    byte readByte() 讀取byte類型的值
    char readChar() 讀取char類型的值
    short readShort() 讀取short類型的值
    int readInt() 讀取int類型的值
    long readLong() 讀取long類型的值
    float readFloat() 讀取float類型的值
    double readDouble() 讀取double類型的值
  • 寫入檔案
    public static void main(String[] args) throws IOException {
        //先建立位元組流通道
        FileOutputStream out = new FileOutputStream("D:\\course\\03-JavaSE\\file\\out.txt");
        DataOutputStream dos = new DataOutputStream(out);
    
        //儲存資料, 用對應類型的"write類型()"方法
        dos.writeInt(456);
        dos.writeDouble(3.14);
        dos.writeBoolean(false);
        dos.writeChar('G');
    
        dos.close();
    }
               
  • 從檔案中按順序讀取:
    public static void main(String[] args) throws IOException {
        FileInputStream in = new FileInputStream("D:\\course\\03-JavaSE\\file\\out.txt");
        DataInputStream dis = new DataInputStream(in);
    
    	//讀取順序要與寫入順序一緻
        int num = dis.readInt();
        double dd = dis.readDouble();
        boolean bb = dis.readBoolean();
        char cc = dis.readChar();
    
        dis.close();
    }
               

5. ObjectInputStream

使用

ObjectInputStream

進行反序列化,簡單的了解為把檔案中的對象讀取出來

  • 對象序列化就是 把一個對象轉換為

    01

    二進制序列,存儲到檔案中,使用

    ObjectOutputStream

  • 對象反序列化就是把一組

    01

    二進制序列轉換為對象,讀取到程式中,使用

    ObjectInputStream

注意:對象序列化/反序列化的前提是對象的類要實作

Serializable

接口。

Serializable

接口是 一個标志接口,沒有任何成員,就是告訴編譯器可以進行序列化。一般情況下,類實作了

Serializable

接口後,需要手動的添加一個序列化版本号字段
public class Person implements Serializable {
	private static final long serialVersionUID = -5990283450992650215L;
}
           
當對象序列化之後,即把對象儲存到檔案之後,又修改了

Person

類的結構,比如說增加了一個新的字段,再進行反序列化時會産生

java.io.InvalidClassException

類無效異常(通過比較

serialVersionUID

序列化版本号字段)
  • 構造方法:
    構造方法 說明
    ObjectInputStream(InputStream in) 通過輸入流InputStream來建立一個 ObjectInputStream。
  • 常用方法:
    方法 說明

    Object readObject()

    從ObjectInputStream讀取一個對象。
  • 對象序列化:
    public static void main(String[] args) throws IOException {
    
        //先建立輸出位元組流
        FileOutputStream out = new FileOutputStream("D:\\course\\03-JavaSE\\file\\obj.txt");
        ObjectOutputStream oos = new ObjectOutputStream(out);
    
        //對象序列化可以簡單的看作是把對象儲存到檔案中
        Person p1 = new Person("lisi", 23);
        oos.writeObject(p1);
    
        oos.close();
    }
               
  • 對象的反序列化:
    public static void main(String[] args) throws IOException, ClassNotFoundException {
        FileInputStream in = new FileInputStream("D:\\course\\03-JavaSE\\file\\obj.txt");
        ObjectInputStream ois = new ObjectInputStream(in);
    
        //readObject()方法傳回值類型是Object類型, 實際從檔案中讀取的是Person對象
        Person obj = (Person) ois.readObject();
    	//如果是多個
    	//List<Person> list = (List<Person>) obj;	    
    
        ois.close();
    
        System.out.println(obj);
    }
               

四、OutputStream及其子類

1. OutputStream

OutputStream

是位元組輸出流基類,抽象類是表示輸出位元組流的所有類的超類。

方法 說明
void write(byte[] b) 将 b.length 個位元組從指定的 byte 數組寫入此輸出流
void write(byte[] b, int off, int len) 将指定 byte 數組中從偏移量 off 開始的 len 個位元組寫入此輸出流

abstract void write(int b)

将指定的位元組寫入此輸出流

void close()

關閉此輸出流并釋放與此流有關的所有系統資源

void flush()

重新整理此輸出流并強制寫出所有緩沖的輸出位元組

注意:輸出的目的地檔案不存在,則會自動建立,不指定盤符的話,預設建立在項目目錄下;輸出換行符時一定要寫

\r\n

不能隻寫

\n

,因為不同文本編輯器對換行符的識别存在差異性。

2. FileOutputStream

FileOutputStream

是位元組檔案輸出流是用于将資料寫入到File,從程式中寫入到其他位置。

  • 構造方法:
    構造方法 說明
    FileOutputStream(File file) 建立檔案輸出流以寫入由指定的 File對象表示的檔案。
    FileOutputStream(File file, boolean append) 建立由指定的 File對象表示的檔案輸出流。Append為true表示以追加的方式寫入
    FileOutputStream(String name) 建立檔案輸出流以指定的名稱寫入檔案。
    FileOutputStream(String name, boolean append) 以指定的名稱建立檔案輸出流,Append為true表示以追加的方式寫入。
  • 常用方法:

    FileOutputStream

    覆寫和重寫了父類的的常用方法。
public static void main(String[] args) {
    try (
            //1)在目前程式與檔案之間建立流通道,如果檔案不存在,系統會建立一個檔案,如果檔案存在,會覆寫檔案中的内容
            //FileOutputStream fos = new FileOutputStream("D:\\course\\03-JavaSE\\file\\def.txt");
            //這裡在後面指定了參數true,一個如果檔案已存在,把就新的内容追加到檔案原有内容的後面,如果檔案不存在,系統也會建立一個檔案
            FileOutputStream fos = new FileOutputStream("D:\\course\\03-JavaSE\\file\\def.txt", true);
    ) {
        //2)把資料寫到檔案中
        //2.1一次寫一個位元組
        fos.write(97);
        fos.write(98);
        fos.write(99);
        //2.2換行, 在Windows作業系統中,換行需要兩個字元\r\n
        fos.write('\r');
        fos.write('\n');
        //2.3 把位元組數組儲存到檔案中
        byte[] bytes = "helloworld".getBytes();
        fos.write(bytes);   //把整個位元組數組中的位元組儲存到檔案中

        fos.write('\r');
        fos.write('\n');
        fos.write(bytes, 0, 5);     //把bytes數組中從0開始的5個位元組儲存到檔案中
    } catch (IOException e) {
        e.printStackTrace();
    }
}

           

3. BufferedOutputStream

BufferedOutputStream

是位元組緩沖輸出流,提高了寫出效率。

  • 構造方法:
    構造方法 說明
    BufferedOutputStream(OutputStream out) 建立一個新的緩沖輸出流,以将資料寫入指定的底層輸出流
    BufferedOutputStream(OutputStream out, int size) 建立一個新的緩沖輸出流,以将具有指定緩沖區大小的資料寫入指定的底層輸出流
  • 常用方法同

    OutputStream

public static void write() throws IOException {
    //1)先建立位元組流
    FileOutputStream fos = new FileOutputStream("D:\\course\\03-JavaSE\\file\\def.txt");
    //對位元組流進行緩沖
    BufferedOutputStream bos = new BufferedOutputStream(fos);

    //2)把資料寫到緩沖流的緩沖區中
    bos.write("hello".getBytes());

    //3)調用flush()
    bos.flush();
    bos.close();
}
           

4. DataOutputStream

DataOutputStream

在向檔案中儲存資料時,可以帶有資料格式(基本類型和String),把帶有格式的資料儲存到檔案中之後,打開檔案會顯示亂碼

  • 構造方法:
    構造方法 說明
    DataOutputStream(OutputStream out) 建立一個DataOutputStream,以将資料寫入指定的底層輸出流
  • 常用方法:
    方法 說明
    void writeBoolean(boolean v) 寫入bollean類型的值
    void writeByte(int v) 寫入byte類型的值
    void writeBytes(String s) 将字元串作為位元組序列寫入
    void writeChar(int v) 寫入char類型的值
    void writeChars(String s) 将字元串作為字元數組寫入
    void writeDouble(double v) 寫入double類型的值
    void writeFloat(float v) 寫入float類型的值
    void writeInt(int v) 寫入int類型的值
    void writeLong(long v) 寫入long類型的值
    void writeShort(int v) 寫入short類型的值

使用例子見

DataInputStream

5. ObjectOutputStream

ObjectOutputStream

将對象序列化到檔案中。

  • 構造方法:
    構造方法 說明
    ObjectOutputStream(OutputStream out) 建立一個ObjectOutputStream,以将資料寫入指定的底層輸出流
  • 常用方法:
    方法 說明
    void writeObject(Object obj) 将指定的對象寫入ObjectOutputStream。

使用例子見

ObjectInputStream

6. PrintStream

  • 構造方法:
    構造方法 說明
    PrintStream(OutputStream out) 預設編碼方式的PrintStream
    PrintStream(OutputStream out, boolean autoFlush) 預設編碼方式,autoFlush為true時自動重新整理,預設不自動重新整理
    PrintStream(OutputStream out, boolean autoFlush, String encoding) 指定編碼方式,autoFlush為true時自動重新整理
    PrintStream(String fileName) 指定檔案名稱
    PrintStream(String fileName, String csn) 指定檔案名稱和字元編碼csn
    PrintStream(File file) 指定檔案對象
    PrintStream(File file, String csn) 指定檔案對象和字元編碼csn
  • 常用方法:
    方法 說明

    void print(任意類型的形參)

    列印

    void println(任意類型的形參)

    列印完後終止行

System

類中

out

屬性就是一個

PringStream

對象
public static void main(String[] args) throws FileNotFoundException {
    FileOutputStream out = new FileOutputStream("D:\\course\\03-JavaSE\\file\\log.txt", true);
    PrintStream ps = new PrintStream(out);

    ps.print("hello");
    ps.println("world");//輸出到檔案

    //System類的out成員就是PrintStream類型的變量,
    //System.out代表系統的标準輸出裝置,即顯示器
    System.out.println("這一行資訊顯示在螢幕上");
    //System.setOut()可以修改System.out的列印方向
    System.setOut(ps);
    System.out.println("這一行資訊不會列印在螢幕上,而是列印到printStream流對應的log.txt檔案中");

    //對于異常的捕獲處理, 在開發時一般把異常資訊列印到螢幕上, 部署後需要把異常資訊列印到日志檔案中
    try {
        new SimpleDateFormat().parse("dsfaf");
    } catch (ParseException e) {
        //e.printStackTrace();//列印到螢幕上
        e.printStackTrace(ps);//列印到檔案
    }

    ps.close();
}
           

五、Reader及其子類

1. Reader

Reader

:讀取字元流的抽象類

方法 說明
int read() 讀取單個字元,如果讀到檔案末尾傳回-1

int read(char[] cbuf)

将字元讀入數組
abstract int read(char[] cbuf, int off, int len) 将字元讀入數組的某一部分
long skip(long n) 跳過字元

abstract void close()

關閉該流并釋放與之關聯的所有資源

2. InputStreamReader

InputStreamReader

是位元組流轉字元流,它使用的字元集可以由名稱指定或顯式給定,否則将接受平台預設的字元集。

  • 構造方法:
    方法 說明
    InputStreamReader(InputStream in) 建立一個使用預設字元集的 InputStreamReader
    InputStreamReader(InputStream in, Charset cs) 建立使用給定字元集的 InputStreamReader
    InputStreamReader(InputStream in, CharsetDecoder dec) 建立使用給定字元集解碼器的 InputStreamReader
    InputStreamReader(InputStream in, String charsetName) 建立使用指定字元集的 InputStreamReader
  • 常用方法:
    方法 說明
    String getEncoding() 傳回此流使用的字元編碼的名稱
public static void main(String[] args) throws IOException {
    //1)建立位元組流, 讀取abc.txt檔案,該檔案的編碼是GBK編碼
    FileInputStream fis = new FileInputStream("D:\\course\\03-JavaSE\\file\\abc.txt");
    //2)把再把位元組流轉換為字元流
    InputStreamReader isr = new InputStreamReader(fis, "GBK");

    //再通過isr字元流讀取檔案的内容
    int cc = isr.read();
    while (cc != -1) {
        System.out.print((char) cc);
        cc = isr.read();
    }
    isr.close();
}
           

3. FileReader

FileReader

InputStreamReader

類的直接子類,以字元為機關讀取檔案中的内容。隻能以預設的編碼方式讀取純文字檔案

  • 構造方法:
    方法 說明
    FileReader(File file) 通過 File建立一個新的 FileReader。
    FileReader(FileDescriptor fd) 通過給定 FileDescriptor建立一個新的 FileReader。
    FileReader(String fileName) 通過檔案的名稱建立一個新的 FileReader。
  • 常用方法同

    InputStreamReader

4. BufferedReader

BufferedReader

是字元緩沖流,從字元輸入流中讀取文本,緩沖各個字元,進而實作字元、數組和行的高效讀取。

  • 構造方法:
    方法 說明
    BufferedReader(Reader in) 建立一個使用預設大小輸入緩沖區的緩沖字元輸入流
    BufferedReader(Reader in, int sz) 建立一個使用指定大小輸入緩沖區的緩沖字元輸入流
  • 常用方法:
    方法 說明

    String readLine()

    一次讀取一行文本,讀到文本末尾傳回
public static void main(String[] args) throws IOException {
    //讀取abc.txt檔案,該檔案是GBK編碼
    InputStreamReader fr = new InputStreamReader(new FileInputStream("D:\\course\\03-JavaSE\\file\\abc.txt"), "GBK");

    //對字元流進行緩沖
    BufferedReader bufferedReader = new BufferedReader(fr);

    //緩沖字元流可以一次讀取一行, 讀到檔案末尾傳回null
    String line = bufferedReader.readLine();
    while (line != null) {
        System.out.println(line);
        line = bufferedReader.readLine();
    }

    bufferedReader.close();
}
           

六、Writer及其子類

1. Writer

Writer

:寫入字元流的抽象類

方法 說明
void write(char[] cbuf) 寫入字元數組
abstract void write(char[] cbuf, int off, int len) 寫入字元數組的某一部分
void write(int c) 寫入單個字元
void write(String str) 寫入字元串
void write(String str, int off, int len) 寫入字元串的某一部分
Writer append(char c) 将指定字元添加到此 writer
Writer append(CharSequence csq) 将指定字元序列添加到此 writer
Writer append(CharSequence csq, int start, int end) 将指定字元序列的子序列添加到此 writer.Appendable

abstract void flush()

重新整理該流的緩沖

abstract void close()

關閉此流,但要先重新整理它

2. OutputStreamWriter

OutputStreamWriter

可以把字元流轉換為指定格式的位元組流,檔案編碼與目前環境編碼不一緻時使用

  • 構造方法:
    方法 說明
    OutputStreamWriter(OutputStream out) 建立使用預設字元編碼的 OutputStreamWriter
    OutputStreamWriter(OutputStream out, Charset cs) 建立使用給定字元集的 OutputStreamWriter
    OutputStreamWriter(OutputStream out, CharsetEncoder enc) 建立使用給定字元集編碼器的 OutputStreamWriter
    OutputStreamWriter(OutputStream out, String charsetName) 建立使用指定字元集的 OutputStreamWriter
  • 特有方法:
    方法 說明
    String getEncoding() 傳回此流使用的字元編碼的名稱
public static void main(String[] args) throws IOException {
    //1)先建立位元組流, 以追加的方式打開abc.txt檔案, 該檔案是GBK編碼
    FileOutputStream fos = new FileOutputStream("D:\\course\\03-JavaSE\\file\\abc.txt", true);
    //2)把字元流轉換為位元組流
    OutputStreamWriter osw = new OutputStreamWriter(fos, "GBK");

    osw.write("\r\n");
    osw.write("這一條語句是從UTF-8編碼環境中寫入到檔案中的");

    osw.close();
}
           

3. FileWriter

FileWriter

OutputStreamWriter

類的直接子類,以字元為機關把資料儲存到檔案中。隻能以預設的編碼方式寫入純文字檔案

  • 構造方法:
    方法 說明
    FileWriter(File file) 給一個File對象構造一個FileWriter對象。
    FileWriter(File file, boolean append) 給一個File對象構造一個FileWriter對象,append為true表示追加
    FileWriter(FileDescriptor fd) 構造與檔案描述符關聯的FileWriter對象。
    FileWriter(String fileName) 構造一個給定檔案名的FileWriter對象。
    FileWriter(String fileName, boolean append) 構造一個FileWriter對象,append為true表示追加。
  • 常用方法同

    OutputStreamWriter

4. BufferedWriter

  • 構造方法:
    方法 說明
    BufferedWriter(Writer out) 建立一個使用預設大小輸出緩沖區的緩沖字元輸出流
    BufferedWriter(Writer out, int sz) 建立一個使用給定大小輸出緩沖區的新緩沖字元輸出流
  • 特有方法:
    方法 說明

    void newLine()

    寫入一個行分隔符
public static void main(String[] args) throws IOException {
    //寫入Abc.txt檔案,該檔案編碼是GBK
    OutputStreamWriter writer = new OutputStreamWriter(new FileOutputStream("D:\\course\\03-JavaSE\\file\\abc.txt", true), "GBK");

    BufferedWriter bufferedWriter = new BufferedWriter(writer);

    bufferedWriter.newLine();//産生一個新行
    bufferedWriter.write("使用緩沖字元流寫入的資料");

    bufferedWriter.close();
}
           

5. PrintWriter

PrintWriter

類可用來建立一個檔案并向文本檔案寫入資料,使用方式與

PrintStream

幾乎是一模一樣的

  • 差別:

    PrintStream

    最終輸出的總是

    byte

    資料,而

    PrintWriter

    則是擴充了

    Writer

    接口,它的

    print()/println()

    方法最終輸出的是

    char

    資料。
  • 構造方法:
    方法 說明
    PrintWriter(File file) 使用指定的檔案建立一個新的PrintWriter,而不需要自動的線路重新整理。
    PrintWriter(File file, String csn) 使用指定的檔案和字元集建立一個新的PrintWriter,而不需要自動進行線條重新整理。
    PrintWriter(OutputStream out) 從現有的OutputStream建立一個新的PrintWriter,而不需要自動線路重新整理。
    PrintWriter(OutputStream out, boolean autoFlush) 從現有的OutputStream建立一個新的PrintWriter。
    PrintWriter(String fileName) 使用指定的檔案名建立一個新的PrintWriter,而不需要自動執行行重新整理。
    PrintWriter(String fileName, String csn) 使用指定的檔案名和字元集建立一個新的PrintWriter,而不需要自動線路重新整理。
    PrintWriter(Writer out) 建立一個新的PrintWriter,沒有自動線沖洗。
    PrintWriter(Writer out, boolean autoFlush) 建立一個新的PrintWriter。