Java FileInputStream.skip()方法

原文:https://www.studytonight.com/java-file-io/java-fileinputstream-skip-method

在本教程中,我们将学习 JavaFileInputStream类的skip()方法。此方法用于跳过并丢弃此FileInputStream中给定数量的字节数据。这是一个非静态方法,在 java.io 包中可用。

句法

这是此方法的语法声明。它接受要跳过的“n”字节数作为参数,并返回跳过的确切字节数。

public long skip(long n)

示例 1:在 Java 中使用 FileInputStream 跳过字节

让我们看一个例子,其中我们使用 FileInputStream 的 skip()方法来跳过字节的数据。请看下面的例子。

import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
public class StudyTonight 
{
    public static void main(String[] args) throws IOException 
    { 
        int i;
        try 
        {
            InputStream inputStream = new FileInputStream("E:\\studytonight\\output.txt");
            while ((i = inputStream.read()) != -1)
            {
                char c = (char) i;
                System.out.print(c + " ");
                inputStream.skip(1);
            }

            inputStream.close();
        } 
        catch (Exception e)
        {
            e.printStackTrace();
        }
    }  
}

hlosyoih

示例 2:在 Java 中使用 FileInputStream 跳过字节

让我们看另一个例子,其中我们使用 FileInputStream 的 skip()方法来跳过文件流中的字节数据。请看下面的例子。

import java.io.*;
public class Studytonight {
 public static void main(String[] args) throws Exception {
  FileInputStream st = null;
  int count = 0;
  try {
   st = new FileInputStream("E:\Studytonight\output.txt");
   while ((count = st.read()) != -1) {   
    count = st.read();    
    byte b = (byte) count;    
    System.out.println("st.read(): " + b);
    long skip_byte = st.skip(2);
    System.out.println("st.skip(2): " + skip_byte);
    System.out.println();
   }
  } catch (Exception ex) {
   System.out.println(ex.toString());
  } finally {

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

ST . read():4 ST . skip(2):2 T3】ST . read():97 ST . skip(2):2 T6】ST . read():111 ST . skip(2):2 T9】ST . read():33 ST . skip(2):2

结论:

在本教程中,我们学习了 JavaFileInputStream 类的skip()方法,该方法从当前输入流中跳过给定的数据字节数,并返回实际跳过的字节数。它只能用类对象访问,如果我们试图用类名访问方法,那么我们会得到一个错误。