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。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。