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.