當前位置: 首頁>>編程示例 >>用法及示例精選 >>正文


Java DataInputStream skipBytes()用法及代碼示例

DataInputStream類skipBytes()方法

  • skipBytes() 方法可在java.io包。
  • skipBytes() 方法用於從該 DataInputStream 跳過給定字節數的數據。
  • skipBytes() 方法是一個非靜態方法,它隻能通過類對象訪問,如果我們嘗試使用類名訪問方法,那麽我們將得到一個錯誤。
  • skipBytes() 方法可能會在跳過數據字節時拋出異常。
    IOException: 獲取任何輸入/輸出錯誤時可能會拋出此異常。

用法:

    public final int skipBytes(int number);

參數:

  • int number– 表示要跳過的字節數。

返回值:

該方法的返回類型是int,它返回要跳過的確切字節數。

例:

// Java program to demonstrate the example 
// of int skipBytes(int number) method of 
// DataInputStream

import java.io.*;

public class SkipBytesOfDIS {
 public static void main(String[] args) throws IOException {
  InputStream is_stm = null;
  DataInputStream dis_stm = null;
  FileOutputStream fos_stm = null;
  DataOutputStream dos_stm = null;
  byte[] b_arr = {
   12,
   20,
   45,
   98,
   75,
   69,
   30,
   58,
   47,
   61,
   83,
   55
  };

  try {
   // Instantiate FileInputStream, 
   // DataInputStream, FileOutputStream
   // and DataOutputStream 

   fos_stm = new FileOutputStream("C:\\Users\\Preeti Jain\\Desktop\\programs\\includehelp.txt");
   dos_stm = new DataOutputStream(fos_stm);

   // Loop to write each byte till end
   for (byte val:b_arr) {
    // By using write() method isto
    // write a byte value to the
    // DataOutputStream dos_stm
    dos_stm.write(val);
   }

   is_stm = new FileInputStream("C:\\Users\\Preeti Jain\\Desktop\\programs\\includehelp.txt");
   dis_stm = new DataInputStream(is_stm);


   // Loop To Read Available Data till end
   while (dis_stm.available() > 0) {
    // By using skipBytes() method is to
    // skip 2 bytes of data from the stream
    dis_stm.skipBytes(2);

    // By using read() method isto read 
    // byte from dis_stm

    int in = dis_stm.read();
    System.out.println("dis_stm.read():" + in );
   }
  } catch (Exception ex) {
   System.out.println(ex.toString());
  } finally {
   // To free system resources linked
   // with these streams
   if (is_stm != null)
    is_stm.close();

   if (dis_stm != null)
    dis_stm.close();

   if (dos_stm != null)
    dos_stm.close();

   if (fos_stm != null)
    fos_stm.close();
  }
 }
}

輸出

dis_stm.read():45
dis_stm.read():69
dis_stm.read():47
dis_stm.read():55


相關用法


注:本文由純淨天空篩選整理自Preeti Jain大神的英文原創作品 Java DataInputStream skipBytes() Method with Example。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。