Java FileInputStream available()方法

java.io.FilterInputStream.available() 用于返回可以从输入流读取的估计字节数。

1 语法

public int available()

2 参数

3 返回值

返回可以读取的字节数的估计值。

4 示例 

package com.yiidian;

/**
 * 一点教程网: http://www.yiidian.com
 */
/**
 * java.io.FilterInputStream.available()方法的例子
 */
import java.io.BufferedInputStream;
import java.io.FileInputStream;
import java.io.FilterInputStream;
import java.io.IOException;
import java.io.InputStream;

public class Demo {
    public static void main(String[] args) throws IOException {
        InputStream is = null;
        FilterInputStream fis = null;
        int i = 0, j = 0;
        char c;

        try {
            // create input streams
            is = new FileInputStream("d://test.txt");
            fis = new BufferedInputStream(is);

            // read till the end of the file
            while((i = fis.read())!=-1) {

                // converts integer to character
                c = (char)i;

                // prints
                System.out.print("Read: "+c);

                // number of bytes available
                j = fis.available();

                // prints
                System.out.println("; Available bytes: "+j);
            }

        } catch(Exception e) {
            // if any error occurs
            e.printStackTrace();
        } finally {
            // releases any system resources associated with the stream
            if(is!=null)
                is.close();
            if(fis!=null)
                fis.close();
        }
    }
}

假设test.txt的内容如下:

ABCDE

输出结果为:

Read: A; Available bytes: 4
Read: B; Available bytes: 3
Read: C; Available bytes: 2
Read: D; Available bytes: 1
Read: E; Available bytes: 0

热门文章

优秀文章