Java.io.RandomAccessFile.readFully() 方法



描述

java.io.RandomAccessFile.readFully(byte[] b,int off,int len) 方法从该文件读取正好 len 个字节到字节数组中,从当前文件指针开始。此方法反复从文件中读取,直到读取到请求的字节数。

声明

以下是 java.io.RandomAccessFile.readFully() 方法的声明。

public final void readFully(byte[] b,int off,int len)

参数

  • b - 读取数据的缓冲区。

  • off - 数据的起始偏移量。

  • len - 要读取的字节数。

返回值

此方法不返回值。

异常

  • 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[10];

         // read the file
         raf.readFully(arr, 3, 7);

         // 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
java_io_randomaccessfile.htm
广告

© . All rights reserved.