此类的实例支持对随机访问文件的读取和写入。随机访问文件的行为类似存储在文件系统中的一个大型 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实例打开的文件。
1 import java.io.RandomAccessFile;
2
3 public class Main {
4 public static void main(String[] args) throws Exception {
5 RandomAccessFile randomAccessFile = new RandomAccessFile("hello.txt","rw") ;
6 randomAccessFile.close();
7 }
8 }
seek() 文件指针移动。
1 import java.io.RandomAccessFile;
2
3 public class Main {
4 public static void main(String[] args) throws Exception {
5 RandomAccessFile randomAccessFile = new RandomAccessFile("hello.txt","rw") ;
6 // seek 参数为 long
7 long w = 100 ;
8 randomAccessFile.seek(w);
9 randomAccessFile.close();
10 }
11 }
length() 文件长度
1 import java.io.RandomAccessFile;
2
3 public class Main {
4 public static void main(String[] args) throws Exception {
5 RandomAccessFile randomAccessFile = new RandomAccessFile("hello.txt","rw") ;
6 long 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对文件进行切分,从大文件的不同位置开线程进行读写。