FileInputStream 类的 available() 方法用于返回可以从输入流中读取而不会阻塞的估计剩余字节数。此方法返回要从文件中读取的剩余字节数。当一个文件被完全读取时,这个函数返回零。
用法:
FileInputStream available()
返回值:该方法返回并估计从该输入流中读取的剩余字节数而不阻塞。
异常:该方法可以产生IOException或FileNotFoundException等异常。这些异常如下所述。
- IOException -如果文件输入流已通过调用 close 关闭或发生任何 I/O 错误。
- FileNotFoundException -如果该目录不可用,那么我们将得到 FileNotFoundException。
如何调用 available() 方法?
第 1 步:将文件附加到 FileInputStream,因为这将使我们能够从文件中读取数据,如下所示:
FileInputStream fileInputStream = new FileInputStream(“file.txt”);
第 2 步:现在,要从文件中读取有多少数据可供读取的数据,我们应该使用 FileInputStream 对象调用一个可用的方法,如下所示;
int ch = fileInputStream.available();
Step 3(a):当没有更多数据可供进一步读取时,available()方法返回0;
步骤 3(b):然后,我们应该将监视器附加到输出流。为了显示数据,我们可以使用 System.out.print。
System.out.print(ch);
Implementation
原始文件内容:file.txt
GeeksforGeeks
该程序将读取一个文件并返回每次读取的字符数。
Java
// Java program to demonstrate the working
// of the FileInputStream available() method
import java.io.File;
import java.io.FileInputStream;
public class abc {
public static void main(String[] args)
{
// Creating file object and specifying path
File file = new File("file.txt");
try {
FileInputStream input = new FileInputStream(file);
int character;
// read character by character by default
// read() function return int between 0 and 255.
while ((character = input.read()) != -1) {
int ch = input.available();
System.out.print("Currently Reading:"
+ (char)character);
System.out.print(" Remaining character:"
+ ch);
System.out.println();
}
input.close();
}
catch (Exception e) {
e.printStackTrace();
}
}
}
输出
Currently Reading:G Remaining character:12 Currently Reading:e Remaining character:11 Currently Reading:e Remaining character:10 Currently Reading:k Remaining character:9 Currently Reading:s Remaining character:8 Currently Reading:f Remaining character:7 Currently Reading:o Remaining character:6 Currently Reading:r Remaining character:5 Currently Reading:G Remaining character:4 Currently Reading:e Remaining character:3 Currently Reading:e Remaining character:2 Currently Reading:k Remaining character:1 Currently Reading:s Remaining character:0
相关用法
- Java FileInputStream read()用法及代码示例
- Java FileInputStream close()用法及代码示例
- Java FileInputStream getFD()用法及代码示例
- Java FileInputStream finalize()用法及代码示例
- Java FileInputStream skip()用法及代码示例
- Java FileInputStream getChannel()用法及代码示例
- Java ByteArrayInputStream available()用法及代码示例
- Java ObjectInputStream available()用法及代码示例
- Java PushbackInputStream available()用法及代码示例
- Java BufferedInputStream available()用法及代码示例
- Java Java lang.Long.lowestOneBit()用法及代码示例
- Java Java lang.Long.numberOfTrailingZeros()用法及代码示例
- Java Java lang.Long.numberOfLeadingZeros()用法及代码示例
- Java Java lang.Long.highestOneBit()用法及代码示例
注:本文由纯净天空筛选整理自akshitsaxenaa09大神的英文原创作品 FileInputStream available() Method in Java with Examples。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。