Java.io.RandomAccessFile.readInt() 方法



描述

java.io.RandomAccessFile.readInt() 方法從此檔案中讀取一個帶符號的 32 位整數。此方法從檔案讀取 4 個位元組,從當前檔案指標開始。

宣告

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

public final int readInt()

引數

返回值

此方法返回此檔案的接下來的四個位元組,解釋為一個 int。

異常

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

  • EOFException − 如果此檔案在讀取四個位元組之前到達檔案末尾。

示例

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

package com.tutorialspoint;

import java.io.*;

public class RandomAccessFileDemo {
   public static void main(String[] args) {

      try {
         int i = 284;
         
         // create a new RandomAccessFile with filename test
         RandomAccessFile raf = new RandomAccessFile("c:/test.txt", "rw");

         // write something in the file
         raf.writeInt(123);

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

         // print the int
         System.out.println("" + raf.readInt());

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

         // write something in the file
         raf.writeInt(i);

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

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

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

ABCDE  

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

123
284
java_io_randomaccessfile.htm
廣告