Java.io.OutputStreamWriter.close() 方法



描述

java.io.OutputStreamWriter.close() 方法關閉流,並首先重新整理它。流關閉後,進一步的 write() 或 flush() 呼叫將導致丟擲 IOException。關閉之前已關閉的流沒有任何效果。

宣告

以下是 java.io.OutputStreamWriter.close() 方法的宣告。

public void close()

引數

返回值

此方法不返回值。

異常

IOException − 如果發生 I/O 錯誤。

示例

以下示例顯示了 java.io.OutputStreamWriter.close() 方法的使用。

package com.tutorialspoint;

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.
java_io_outputstreamwriter.htm
廣告

© . All rights reserved.