Java RandomAccessFile

这个类用于读写随机访问文件。随机访问文件的行为类似于一个大的字节数组。有一个隐含的指向数组的光标称为文件指针,通过移动光标进行读写操作。如果在读取所需字节数之前到达文件末尾,则会抛出EOFException异常。它是IOException的一种类型。

构造函数

构造器描述
RandomAccessFile(File file, String mode)创建一个随机访问文件流,以从 File 参数指定的文件中读取,并可选择写入文件。
RandomAccessFile(String name, String mode)创建一个随机访问文件流以从具有指定名称的文件中读取,并可选择写入。

方法

Modifier and TypeMethodMethod
voidclose()它关闭此随机访问文件流并释放与该流关联的所有系统资源。
FileChannelgetChannel()它返回与此文件关联的唯一FileChannel对象。
intreadInt()它从该文件中读取一个带符号的 32 位整数。
StringreadUTF()它从这个文件中读入一个字符串。
voidseek(long pos)它设置文件指针偏移量,从该文件的开头开始测量,下一次读取或写入发生在该位置。
voidwriteDouble(double v)它使用 Double 类中的 doubleToLongBits 方法将 double 参数转换为 long,然后将该 long 值作为八字节量写入文件,高字节在前。
voidwriteFloat(float v)它使用 Float 类中的 floatToIntBits 方法将 float 参数转换为 int,然后将该 int 值作为四字节量(高字节在前)写入文件。
voidwrite(int b)它将指定的字节写入此文件。
intread()它从该文件中读取一个字节的数据。
longlength()它返回此文件的长度。
voidseek(long pos)它设置文件指针偏移量,从该文件的开头开始测量,下一次读取或写入发生在该位置。

示例

import java.io.IOException;  
import java.io.RandomAccessFile;  
  
public class RandomAccessFileExample {  
    static final String FILEPATH ="myFile.TXT";  
    public static void main(String[] args) {  
        try {  
            System.out.println(new String(readFromFile(FILEPATH, 0, 18)));  
            writeToFile(FILEPATH, "I love my country and my people", 31);  
        } catch (IOException e) {  
            e.printStackTrace();  
        }  
    }  
    private static byte[] readFromFile(String filePath, int position, int size)  
            throws IOException {  
        RandomAccessFile file = new RandomAccessFile(filePath, "r");  
        file.seek(position);  
        byte[] bytes = new byte[size];  
        file.read(bytes);  
        file.close();  
        return bytes;  
    }  
    private static void writeToFile(String filePath, String data, int position)  
            throws IOException {  
        RandomAccessFile file = new RandomAccessFile(filePath, "rw");  
        file.seek(position);  
        file.write(data.getBytes());  
        file.close();  
    }  
}  

myFile.TXT文件包含文本“This class is used for reading and writing to random access file.”

运行程序后,它将包含:

This class is used for reading I love my country and my peoplele.

标签: java, Java面试题, Java下载, java教程, java技术, Java学习, Java学习教程, Java语言, Java开发, Java入门教程, Java进阶教程, Java高级教程, Java笔试题, Java编程思想