Java RandomAccessFile 类2025年3月26日 | 阅读 2 分钟 这个类用于读写随机存取文件。随机存取文件就像一个大型的字节数组。数组中有一个隐含的光标,称为文件指针,通过移动光标,我们可以进行读写操作。如果在读取所需字节数之前到达文件末尾,则会抛出 EOFException。它是一种 IOException。 构造函数构造函数 | 描述 |
---|
RandomAccessFile(File file, String mode) | 创建一个随机存取文件流,用于从 File 参数指定的文件中读取,并可选择写入。 | RandomAccessFile(String name, String mode) | 创建一个随机存取文件流,用于从指定名称的文件中读取,并可选择写入。 |
方法修饰符和类型 | 方法 | 方法 |
---|
void | close() | 它关闭此随机存取文件流并释放与该流关联的所有系统资源。 | FileChannel | getChannel() | 它返回与此文件关联的唯一FileChannel对象。 | int | readInt() | 它从该文件中读取一个有符号的 32 位整数。 | String | readUTF() | 它从该文件中读取一个字符串。 | void | seek(long pos) | 它设置文件指针偏移量,从文件开头测量,下一次读写将在此处发生。 | void | writeDouble(double v) | 它使用 Double 类中的 doubleToLongBits 方法将 double 参数转换为 long,然后将该 long 值作为八字节数量写入文件,高字节在前。 | void | writeFloat(float v) | 它使用 Float 类中的 floatToIntBits 方法将 float 参数转换为 int,然后将该 int 值作为四字节数量写入文件,高字节在前。 | void | write(int b) | 它将指定的字节写入此文件。 | int | read() | 它从该文件中读取一个字节数据。 | long | length() | 它返回此文件的长度。 | void | seek(long pos) | 它设置文件指针偏移量,从文件开头测量,下一次读写将在此处发生。 |
示例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. |