Java.io.RandomAccessFile.readFully() 方法



描述

java.io.RandomAccessFile.readFully(byte[] b) 方法從該檔案讀取 b.length 個位元組到位元組陣列中,從當前檔案指標開始。此方法會重複從檔案中讀取資料,直到讀取到所需數量的位元組。

宣告

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

public final void readFully(byte[] b)

引數

  • b -- 讀取資料到的緩衝區。

返回值

此方法不返回值。

異常

  • IOException − 如果發生 I/O 錯誤。如果已到達檔案末尾則不會丟擲。

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

示例

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

package com.tutorialspoint;

import java.io.*;

public class RandomAccessFileDemo {
   public static void main(String[] args) {
   
      try {
         // create a string and a byte array
         String s = "Hello world";

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

         // write something in the file
         raf.writeUTF(s);

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

         // create an array equal to the length of raf
         byte[] arr = new byte[(int) raf.length()];

         // read the file
         raf.readFully(arr);

         // create a new string based on arr
         String s2 = new String(arr);

         // print it
         System.out.println("" + s2);
      } catch (IOException ex) {
         ex.printStackTrace();
      }
   }
}

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

ABCDE  

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

Hello world
java_io_randomaccessfile.htm
廣告
© . All rights reserved.