Java.io.RandomAccessFile.seek() 方法



描述

java.io.RandomAccessFile.seek(long pos) 方法設定檔案指標偏移量,該偏移量以檔案開頭為基準,用於指示下一次讀取或寫入操作發生的位置。偏移量可以設定為超出檔案末尾。將偏移量設定為超出檔案末尾不會更改檔案長度。只有在將偏移量設定為超出檔案末尾後進行寫入時,檔案長度才會發生變化。

宣告

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

public void seek(long pos)

引數

pos − 偏移位置,以位元組為單位,從檔案開頭計算,用於設定檔案指標的位置。

返回值

此方法不返回值。

異常

IOException − 如果 pos 小於 0 或發生 I/O 錯誤。

示例

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

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 5 position
         raf.seek(5);

         // write something in the file
         raf.writeUTF("This is an example");

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

         // print the string
         System.out.println("" + raf.readUTF());
         
      } catch (IOException ex) {
         ex.printStackTrace();
      }
   }
}

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

ABCDE  

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

Hello World
Hel This i
java_io_randomaccessfile.htm
廣告

© . All rights reserved.