admin管理员组

文章数量:1794759

java中available用法

java中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

本文标签: java