java bufferedinputstream关闭_Java BufferedInputStream close()用法及代码示例

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值