當前位置: 首頁>>編程示例 >>用法及示例精選 >>正文


Java OutputStreamWriter close()用法及代碼示例

OutputStreamWriter類close()方法

  • close() 方法可在java.io包。
  • close() 方法用於在關閉流之前先刷新,關閉流後調用的方法 write() 或 flush() 將導致異常。
  • close() 方法是一個非靜態方法,它隻能通過類對象訪問,如果我們嘗試使用類名訪問方法,那麽我們將得到一個錯誤。
  • close() 方法可能會在關閉流時拋出異常。
    IOException:在執行時遇到任何輸入/輸出錯誤時可能會拋出此異常。

用法:

    public void close();

參數:

  • 它不接受任何參數。

返回值:

該方法的返回類型是void,它什麽都不返回。

例:

// Java program to demonstrate the example 
// of void close() method 
// of OutputStreamWriter

import java.io.*;

public class CloseOfOSW {
 public static void main(String[] args) throws Exception {
  OutputStream os_stm = null;
  OutputStreamWriter osw_stm = null;
  InputStream is_stm = null;
  int val = 65;
  try {

   // Instantiates FileOutputStream and 
   // FileInputStream and OutputStreamWriter
   os_stm = new FileOutputStream("D:\\includehelp.txt");
   osw_stm = new OutputStreamWriter(os_stm);

   // Loop to write byte to the stream
   for (int i = 0; i < 3; ++i) {
    osw_stm.write(val);
    val++;
   }
   // By using flush() method is to
   // flush the stream
   osw_stm.flush();
   
   is_stm = new FileInputStream("D:\\includehelp.txt");

   // Loop to read byte from the stream
   for (int i = 0; i < 3; ++i) {
    char ch = (char) is_stm.read();
    System.out.println("ch:" + ch);
   }
   osw_stm.close();
   System.out.println("Stream Closed Successfully....");
  } catch (Exception ex) {
   System.out.println(ex.toString());

  } finally {
   // with the help of this block is to
   // free all necessary resources linked
   // with the stream
   if (is_stm != null) {
    is_stm.close();
    if (os_stm != null) {
     os_stm.close();
    }
   }
  }
 }
}

輸出

ch:A
ch:B
ch:C
Stream Closed Successfully....


相關用法


注:本文由純淨天空篩選整理自Preeti Jain大神的英文原創作品 Java OutputStreamWriter close() Method with Example。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。