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


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

ObjectInputStream類skipBytes()方法

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

用法:

    public int skipBytes(int number);

參數:

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

返回值:

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

例:

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

import java.io.*;

public class SkipBytesOfOIS {
 public static void main(String[] args) throws Exception {
  // Instantiates ObjectOutputStream , ObjectInputStream 
  // FileInputStream and FileOutputStream
  FileOutputStream file_out_stm = new FileOutputStream("D:\\includehelp.txt");
  ObjectOutputStream obj_out_stm = new ObjectOutputStream(file_out_stm);
  FileInputStream file_in_stm = new FileInputStream("D:\\includehelp.txt");
  ObjectInputStream obj_in_stm = new ObjectInputStream(file_in_stm);

  // By using writeUTF() method is to write
  // the encoded string in UTF-8 to the 
  // obj_out_stm stream
  obj_out_stm.writeUTF("JAVA WORLD");

  obj_out_stm.flush();

  // By using skipBytes() method is to skip
  // bytes of data to the stream	
  int skip_byte = obj_in_stm.skipBytes(2);
  System.out.println("obj_in_stm.skipBytes(2):" + skip_byte);

  while (obj_in_stm.available() > 0) {
   // By using readByte() method is to read
   // corresponding byte from the obj_in_stm 
   byte val = (byte) obj_in_stm.readByte();
   System.out.println("obj_in_stm.readByte():" + val);
  }

  // By using close() method is to 
  // close all the streams 
  file_in_stm.close();
  file_out_stm.close();
  obj_in_stm.close();
  obj_out_stm.close();
 }
}

輸出

obj_in_stm.skipBytes(2):2
obj_in_stm.readByte():74
obj_in_stm.readByte():65
obj_in_stm.readByte():86
obj_in_stm.readByte():65
obj_in_stm.readByte():32
obj_in_stm.readByte():87
obj_in_stm.readByte():79
obj_in_stm.readByte():82
obj_in_stm.readByte():76
obj_in_stm.readByte():68


相關用法


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