Java RandomAccessFile
RandomAccessFile用于读取和写入随机访问文件。随机访问文件的行为就像一个大的array个字节。有一个游标隐含在名为文件pointer的数组中,通过移动游标我们执行了读写操作。如果在读取所需的字节数之前已到达文件末尾,则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) |
它设置文件指针偏移量,从该文件的开头开始测量,在该位置下一次读取或写入。 |
示例
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包含文本"该类用于读写随机访问文件。"
在运行程序后它将包含
该类为了读书,我爱我的国家和人民。