Java.io.OutputStreamWriter.close()方法實例
java.io.OutputStreamWriter.close() 方法關閉流,但要先刷新它。一旦流已關閉,進一步調用write() or flush() 會導致一個IOException異常被拋出。關閉以前關閉的流無效。
聲明
以下是java.io.OutputStreamWriter.close()方法聲明
public void close()
參數
-
NA
返回值
此方法無返回值。
異常
-
IOException -- 如果發生I/ O錯誤。
例子
下麵的示例演示java.io.OutputStreamWriter.close()方法的用法。
package com.yiibai; import java.io.*; public class OutputStreamWriterDemo { public static void main(String[] args) { try { // create a new OutputStreamWriter OutputStream os = new FileOutputStream("test.txt"); OutputStreamWriter writer = new OutputStreamWriter(os); // create a new FileInputStream to read what we write FileInputStream in = new FileInputStream("test.txt"); // write something in the file writer.write(70); // flush the stream writer.flush(); // read what we write System.out.println("" + (char) in.read()); // close the stream System.out.println("Closing Stream..."); writer.close(); System.out.println("Stream closed."); } catch (Exception ex) { ex.printStackTrace(); } } }
讓我們編譯和運行上麵的程序,這將產生以下結果:
F Closing Stream... Stream closed.