java.io.RandomAccessFile.read((byte[] b,int off,int len) 方法从此文件读取多达len个字节数据到一个字节数组。
声明
以下是java.io.RandomAccessFile.read()方法的声明
public int read(byte[] b,int off,int len)
参数
-
b -- 数据被读出缓冲器中。
-
off -- 在数组b在其中写入数据的起始位置的偏移。
-
len -- 读出的最大字节数。
返回值
此方法将返回读入缓冲区的总字节数,或如果没有更多的数据,因为该文件的末尾已到达返回-1。
异常
-
IOException --如果发生I/ O错误。如果已经达到文件结束不会抛出。
-
NullPointerException -- 如果b为null。
-
IndexOutOfBoundsException -- 如果off为负,len为负,或len大于b.length- off。
例子
下面的示例演示java.io.RandomAccessFile.read()方法的用法。
package com.yiibai; import java.io.*; public class RandomAccessFileDemo { public static void main(String[] args) { try { byte[] b1 = {1, 2, 3}; byte[] b2 = {1, 2, 3, 4, 5, 6, 7, 8}; // 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); // read 2 bytes, starting from 1 System.out.println("" + raf.read(b1, 1, 2)); // set the file pointer at 0 position raf.seek(0); // read 3 bytes, starting from 4rth System.out.println("" + raf.read(b2, 4, 3)); } catch (IOException ex) { ex.printStackTrace(); } } }
假设我们有一个文本文件c:/ test.txt,它具有以下内容。该文件将被用作输入到我们的示例程序:
ABCDE
让我们编译和运行上面的程序,这将产生以下结果:
2 3