Java FilterInputStream .available()方法

原文:https://www.studytonight.com/java-file-io/java-filterinputstream-available-method

在本教程中,我们将学习 JavaFilterInputStream 类的available()方法。此方法用于返回可从当前FilterInputStream中读取的可用字节总数,而不会被此方法的下一次调用中断,调用程序可以是同一个线程或另一个线程。

句法

这是此方法的语法声明。它不接受任何参数。它返回可以从给定输入流中读取的字节总数。

public int available() throws IOException

示例 1:在 Java 中查找可用字节

在下面的例子中,我们使用 available()方法从文件中获取可读取的字节。由于给定的文件输出.txt 包含 6 个字节用于读取,它将相应地给出输出。

package com.studytonight;

import java.io.BufferedInputStream;
import java.io.FileInputStream;
import java.io.FilterInputStream;
import java.io.IOException;
import java.io.InputStream;

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

      try {

         is = new FileInputStream("E:/studytonight/output.txt");
         st = new BufferedInputStream(is);

         while((i = st.read())!=-1) {

            c = (char)i;

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

            j = st.available();

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

      } catch(Exception e) {

         e.printStackTrace();
      } finally {

         if(is!=null)
            is.close();
         if(st!=null)
            st.close();
      }
   }
}

输出. txt

CURIOUS

读作:C;可用字节:6 读取:U;可用字节:5 读:R;可用字节:4 读:I;可用字节:3 读:0;可用字节:2 读取:U;可用字节:1 读取:S;可用字节:0

示例 1:在 Java 中查找可用字节

在下面的例子中,我们使用 available()方法从文件中获取可读取的字节。由于给定的文件输出.txt 包含 7 个要读取的字节,它将相应地给出输出。

import java.io.*;

public class Studytonight {
 public static void main(String[] args) throws Exception {
  FileInputStream st = null;
  FilterInputStream std = null;
  int count = 0;

  try {

   st = new FileInputStream("E:\Studytonight\output.txt");
   std = new BufferedInputStream(st);

   while ((count = st.read()) != -1) {

    int avail_bytes = st.available();

    byte b = (byte) count;

    System.out.print("st.available(): " + avail_bytes);
    System.out.println(" : " + "byte: " + b);
   }
  } catch (Exception ex) {
   System.out.println(ex.toString());
  } finally {

   if (st != null) {
    st.close();

    if (std != null) {
     std.close();
    }
   }
  }
 }
}

st.available(): 6:字节:100 st.available(): 5:字节:74 st.available(): 4:字节:118 st.available(): 3:字节:32 st.available(): 2:字节:46 st.available(): 1:字节:46 st.available(): 0:字节:46

mail结论

在本教程中,我们学习了 JavaFilterInputStream 类的available()方法,该方法返回可从给定FileInputStream中读取的剩余字节总数。它是 java.io 包中可用的非静态方法,只能用类对象访问,如果我们试图用类名访问该方法,那么我们将会得到一个错误。