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 Java.io.FileInputStream用法及代碼示例
- Java FileInputStream和ObjectInputStream的區別用法及代碼示例
- Java FileInputStream和FileReader的區別用法及代碼示例
- 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。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。