Java中BufferedInputStream類的close()方法關閉輸入流並釋放與之關聯的所有係統資源。調用close()方法後,將禁止從任何輸入文件讀取數據,並且係統將引發IOException。為了解決該問題,用戶可以使用try-catch塊來捕獲任何此類異常並拋出正確的指令。
用法:
public void close()
參數:此方法不接受任何參數。
返回值:此方法不返回任何值。
重寫:該方法在類FilterInputStream中被close覆蓋。
異常:如果發生任何輸入輸出錯誤,則此方法將引發IOException。
以下示例程序旨在說明IO包中BufferedInputStream類中的close()方法:
程序1:假設存在文件“c:/demo.txt”。
// Java program to illustrate
// BufferedInputStream.close() method
import java.io.*;
public class GFG {
public static void main(String[] args)
throws IOException
{
// Create input stream 'demo.txt'
// for reading containing
// text "GEEKSFORGEEKS"
FileInputStream inputStream
= new FileInputStream("c:/demo.txt");
// Convert inputStream to
// bufferedInputStream
BufferedInputStream buffInputStr
= new BufferedInputStream(inputStream);
// Get the number of bytes available
// to read using available() method
int rem_byte = buffInputStr.available();
// Number of bytes available is printed
System.out.println(
"Remaining Byte:" + rem_byte);
// Close the file
buffInputStr.close();
}
}
輸出:
Remaining Byte:13
程序2:假設存在文件“c:/demo.txt”。
// Java program to illustrate
// BufferedInputStream.close() method
import java.io.*;
public class GFG {
public static void main(String[] args)
throws IOException
{
try {
// create input stream 'demo.txt'
// for reading containing
// text "GEEKS"
FileInputStream inputStream
= new FileInputStream(
"c:/demo.txt");
// convert inputStream to
// bufferedInputStream
BufferedInputStream buffInputStr
= new BufferedInputStream(
inputStream);
// get the number of bytes available
// to read using available() method
int rem_byte
= buffInputStr.available();
// number of bytes available is printed
System.out.println(rem_byte);
// close the file
buffInputStr.close();
// now throws io exception
// if available() is invoked
// after close()
rem_byte = buffInputStr.available();
System.out.println(rem_byte);
}
catch (IOException e) {
// exception occurred.
System.out.println(
"Error:Sorry 'buffInputStr'"
+ " is closed");
}
}
}
輸出:
5 Error:Sorry 'buffInputStr' is closed
參考文獻: https://docs.oracle.com/javase/10/docs/api/java/io/BufferedInputStream.html#close()
相關用法
- Java BufferedInputStream mark()用法及代碼示例
- Java BufferedInputStream markSupported()用法及代碼示例
- Java BufferedInputStream skip(long)用法及代碼示例
- Java Scanner close()用法及代碼示例
- Java ByteArrayInputStream close()用法及代碼示例
- Java Reader close()用法及代碼示例
- Java StringWriter close()用法及代碼示例
- Java CharArrayWriter close()用法及代碼示例
- Java ObjectInputStream close()用法及代碼示例
- Java PrintWriter close()用法及代碼示例
- Java StringReader close()用法及代碼示例
- Java Formatter close()用法及代碼示例
- Java PrintStream close()用法及代碼示例
- Java CharArrayReader close()用法及代碼示例
- Java Writer close()用法及代碼示例
注:本文由純淨天空篩選整理自pp_pankaj大神的英文原創作品 BufferedInputStream close() method in Java with Examples。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。