Java.io.RandomAccessFile.skipBytes() 方法



描述

java.io.RandomAccessFile.skipBytes(int n) 方法嘗試跳過 n 個位元組的輸入,丟棄跳過的位元組。此方法可能會跳過較少數量的位元組,甚至可能為零。這可能是由多種條件導致的;在跳過 n 個位元組之前到達檔案末尾只是一種可能性。此方法從不丟擲 EOFException。返回實際跳過的位元組數。如果 n 為負數,則不跳過任何位元組。

宣告

以下是 java.io.RandomAccessFile.skipBytes() 方法的宣告。

public int skipBytes(int n)

引數

n − 要跳過的位元組數。

返回值

此方法返回實際跳過的位元組數。

異常

IOException − 如果發生 I/O 錯誤。

示例

以下示例演示了 java.io.RandomAccessFile.skipBytes() 方法的使用。

package com.tutorialspoint;

import java.io.*;

public class RandomAccessFileDemo {
   public static void main(String[] args) {
   
      try {
         // create a new RandomAccessFile with filename test
         RandomAccessFile raf = new RandomAccessFile("c:/test.txt", "rw");

         // write something in the file
         raf.writeUTF("Hello World");

         // set the file pointer at 0 position
         raf.seek(0);

         // print the string
         System.out.println("" + raf.readUTF());

         // set the file pointer at 0 position
         raf.seek(0);

         // attempt to skip 10 bytes and print the number of bytes skipped
         System.out.println("" + raf.skipBytes(10));

         // print what is left after skipping
         System.out.println("" + raf.readLine());

         // set the file pointer to position 8
         raf.seek(8);

         // attempt to skip 10 more bytes and print the number of bytes skipped
         System.out.println("" + raf.skipBytes(10));
         
      } catch (IOException ex) {
         ex.printStackTrace();
      }
   }
}

假設我們有一個文字檔案 c:/test.txt,其內容如下。此檔案將用作我們示例程式的輸入 -

ABCDE  

讓我們編譯並執行以上程式,這將產生以下結果 -

Hello World
10
rld
5
java_io_randomaccessfile.htm
廣告

© . All rights reserved.