Java.io.FileInputStream.available() 方法
描述
java.io.FileInputStream.available() 方法返回可以从此输入流中读取的剩余字节数,而不会被此输入流的下一个方法调用阻塞。 下一个方法调用也可以是另一个线程。
声明
以下是 java.io.FileInputStream.available() 方法的声明 −
public int available()
参数
NA
返回值
这些方法返回并估计可以在不阻塞的情况下从此输入流中读取的剩余字节数。
异常
IOException − 如果文件输入流已经通过调用 close 关闭或发生任何 I/O 错误。
示例
下面的例子展示了 java.io.FileInputStream.available() 方法的使用。
package com.tutorialspoint;
import java.io.IOException;
import java.io.FileInputStream;
public class FileInputStreamDemo {
public static void main(String[] args) throws IOException {
FileInputStream fis = null;
int available = 0;
int i = 0;
try {
// create new file input stream
fis = new FileInputStream("C://test.txt");
// read till the end of the stream
while((i = fis.read())!=-1) {
// available bytes
available = fis.available();
// convert integer to character
char c = (char)i;
// prints
System.out.print("Available: "+available);
System.out.println("; Read: "+c);
}
} catch(Exception ex) {
// if an I/O error occurs
ex.printStackTrace();
} finally {
// releases all system resources from the streams
if(fis!=null) {
fis.close();
}
}
}
}
假设我们有一个文本文件c:/test.txt,其内容如下。 该文件将用作我们示例程序的输入 −
ABCDEF
让我们编译并运行上面的程序,这将产生下面的结果 −
Available: 5; Read: A Available: 4; Read: B Available: 3; Read: C Available: 2; Read: D Available: 1; Read: E Available: 0; Read: F

