RandomAccessFile详解

合集下载
  1. 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
  2. 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
  3. 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。

RandomAccessFile详解
此类的实例⽀持对随机访问⽂件的读取和写⼊。

随机访问⽂件的⾏为类似存储在⽂件系统中的⼀个⼤型 byte 数组。

存在指向该隐含数组的光标或索引,称为⽂件指针;输⼊操作从⽂件指针开始读取字节,并随着对字节的读取⽽前移此⽂件指针。

如果随机访问⽂件以读取/写⼊模式创建,则输出操作也可⽤;输出操作从⽂件指针开始写⼊字节,并随着对字节的写⼊⽽前移此⽂件指针。

写⼊隐含数组的当前末尾之后的输出操作导致该数组扩展。

该⽂件指针可以通过 getFilePointer ⽅法读取,并通过 seek ⽅法设置。

通常,如果此类中的所有读取例程在读取所需数量的字节之前已到达⽂件末尾,则抛出EOFException(是⼀种 IOException)。

如果由于某些原因⽆法读取任何字节,⽽不是在读取所需数量的字节之前已到达⽂件末尾,则抛出 IOException,⽽不是 EOFException。

需要特别指出的是,如果流已被关闭,则可能抛出 IOException。

构造⽅法:
import java.io.File;
import java.io.RandomAccessFile;
public class Main {
public static void main(String[] args) throws Exception {
// 1
RandomAccessFile randomAccessFile = new RandomAccessFile("hello.txt","rw") ;
// 2
File file = new File("hello.txt");
RandomAccessFile randomAccessFile1 = new RandomAccessFile(file,"rw") ;
}
}
⽅法摘要:
close() 关闭RandomAccessFile实例打开的⽂件。

1import java.io.RandomAccessFile;
2
3public class Main {
4public static void main(String[] args) throws Exception {
5 RandomAccessFile randomAccessFile = new RandomAccessFile("hello.txt","rw") ;
6 randomAccessFile.close();
7 }
8 }
seek() ⽂件指针移动。

1import java.io.RandomAccessFile;
2
3public class Main {
4public static void main(String[] args) throws Exception {
5 RandomAccessFile randomAccessFile = new RandomAccessFile("hello.txt","rw") ;
6// seek 参数为 long
7long w = 100 ;
8 randomAccessFile.seek(w);
9 randomAccessFile.close();
10 }
11 }
length() ⽂件长度
1import java.io.RandomAccessFile;
2
3public class Main {
4public static void main(String[] args) throws Exception {
5 RandomAccessFile randomAccessFile = new RandomAccessFile("hello.txt","rw") ;
6long len = randomAccessFile.length();
7 randomAccessFile.close();
8 }
9 }
 读取:
read()
read(byte[] b)
read(byte[] b,int off,int len)
readLine()
readBoolean()
readDouble()
readFloat()
readByte()
readChar()
写⼊:
write(byte []b)
write(byte []b,int off,int len)
write(int b)
writeBoolean(boolean v)
writeByte(int v)
writeBytes(String s)
writeChar(int v)
writeChars(String s)
writeDouble(double v)
writeFloat(float v)
writeInt(int v)
writeLong(long v)
writeShort(int v)
writeUTF(String str)
注: RandomAccessFile可利⽤多线程完成对⼀个⼤⽂件的读写,利⽤seek对⽂件进⾏切分,从⼤⽂件的不同位置开线程进⾏读写。

相关文档
最新文档