java中available用法_Java BufferedInputStream available()用法及代码示例

BufferedInputStream类将新属性添加到其他输入流,从而可以缓冲输入。创建BufferedInputStream时,将创建一个内部缓冲区数组。

BufferedInputStream类的available()方法用于知道可从内部缓冲区阵列读取的字节数,直到出现没有可用数据读取的情况。方法read()的调用将阻塞程序的执行流程,并等待数据可用。

用法:

public int available()

参数:此方法不带任何参数。

返回值:该方法用于返回从该输入流中读取的剩余字节数之和,没有任何阻塞。

异常:如果发生与输入输出有关的错误,或者使用close方法关闭输入流,则该方法将引发IOException。

范例1:下面的程序演示了available()方法的使用,假设存在文件“d:/demo.txt”。

// Java code to illustrate available() method

import java.io.*;

class Testing {

public static void main(String[] args)

throws IOException

{

// create input stream 'demo.txt'

// for reading containing text "GEEKS"

FileInputStream inputStream =

new FileInputStream("d:/demo.txt");

// convert inputStream to

// bufferedInputStream

BufferedInputStream buffInputStr =

new BufferedInputStream(inputStream);

// get the number of bytes available

// to read using available() method

Integer remBytes =

buffInputStr.available();

// Print result

System.out.println(

"Remaining bytes =" + remBytes);

}

}

输出:

5

范例2:下面的程序演示了available()方法的使用,假设存在文件“d:/demo.txt”。

// Java code to illustrate available() method

import java.io.*;

class Testing {

public static void main(String[] args)

throws IOException

{

// create input stream demo.txt

// for reading containing text

// "GEEKSFORGEEKS"

FileInputStream inputStream =

new FileInputStream("d:/demo.txt");

// convert inputStream to

// BufferedInputStream

BufferedInputStream buffInputStr =

new BufferedInputStream(inputStream);

// get the number of bytes available to

// read using available() method

Integer remBytes =

buffInputStr.available();

// Print result

System.out.println(

"Remaining bytes =" + remBytes);

}

}

输出:

13

  • 2
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值