StringWriter 示例

Java StringWriter 類是一個字元流,它從字串緩衝區收集輸出,可用於構造字串。

StringWriter 類擴充套件了 Writer 類。

在 StringWriter 類中,不使用網路套接字和檔案等系統資源,因此不需要關閉 StringWriter。

import java.io.*;  
public class StringWriterDemo {  
    public static void main(String[] args) throws IOException {  
        char[] ary = new char[1024];  
        StringWriter writer = new StringWriter();  
        FileInputStream input = null;  
        BufferedReader buffer = null;  
        input = new FileInputStream("c://stringwriter.txt");  
        buffer = new BufferedReader(new InputStreamReader(input, "UTF-8"));  
        int x;  
        while ((x = buffer.read(ary)) != -1) {  
                   writer.write(ary, 0, x);  
        }  
        System.out.println(writer.toString());        
        writer.close();  
        buffer.close();  
    }  
}

上面的示例幫助我們瞭解 StringWriter 的簡單示例,使用 BufferedReader 從流中讀取檔案資料。