Java - ByteArrayInputStream skip() 方法



描述

Java ByteArrayInputStream skip(long n) 方法跳过输入流中的 n 个字节。

声明

以下是 java.io.ByteArrayInputStream.skip(long n) 方法的声明:

public long skip(long n)

参数

n − 要跳过的字节数

返回值

此方法返回实际跳过的字节数。

异常

示例 1

以下示例演示了如何使用 Java ByteArrayInputStream skip() 方法在迭代数据流时跳过 1 个字节。我们创建了一个名为 buf 的 byte[] 变量并初始化了一些字节。我们创建了一个 ByteArrayInputStream 引用,然后用 buf 变量初始化它。我们在 while 循环中使用 read() 方法读取字节,并在迭代期间跳过 1 个字节,然后打印该值。

package com.tutorialspoint;
import java.io.ByteArrayInputStream;
import java.io.IOException;
public class ByteStreamTest {
   public static void main(String[] args) throws IOException {
      byte[] buf = {65, 66, 67, 68, 69};
      ByteArrayInputStream bais = null;
      
      try {
         // create new byte array input stream
         bais = new ByteArrayInputStream(buf);
         
         int value = 0;
         
         // read till the end of the stream
         while((value = bais.read())!=-1) {
            
            // skip single byte
            bais.skip(1);
            System.out.println(value);
         }
         
      } catch(Exception e) {
         // if I/O error occurs
         e.printStackTrace();
      } finally {
         if(bais!=null)
            bais.close();
      }   
   }
}

输出

让我们编译并运行上述程序,这将产生以下结果:

65
67
69

示例 2

以下示例演示了如何使用 Java ByteArrayInputStream skip() 方法在迭代数据流时跳过多个字节。我们创建了一个名为 buf 的 byte[] 变量并初始化了一些字节。我们创建了一个 ByteArrayInputStream 引用,然后用 buf 变量初始化它。我们在 while 循环中使用 read() 方法读取字节,并在迭代期间跳过 2 个字节,然后打印该值。

package com.tutorialspoint;
import java.io.ByteArrayInputStream;
import java.io.IOException;
public class ByteStreamTest {
   public static void main(String[] args) throws IOException {
      byte[] buf = {65, 66, 67, 68, 69};
      ByteArrayInputStream bais = null;
      
      try {
         // create new byte array input stream
         bais = new ByteArrayInputStream(buf);
         
         int value = 0;
         
         // read till the end of the stream
         while((value = bais.read())!=-1) {
            
            // skip multiple bytes
            bais.skip(2);
            System.out.println(value);
         }
         
      } catch(Exception e) {
         // if I/O error occurs
         e.printStackTrace();
      } finally {
         if(bais!=null)
            bais.close();
      }   
   }
}

输出

让我们编译并运行上述程序,这将产生以下结果:

65
68
java_bytearrayinputstream.htm
广告
© . All rights reserved.