RandomAccessFile
public RandomAccessFile(String name, String mode) throws FileNotFoundException创建从中读取和向其中写入(可选)的随机存取文件流,该文件具有指定名称。将创建一个新的
FileDescriptor
对象来表示到文件的连接。
mode 参数指定用以打开文件的访问模式。允许的值及其含意如 RandomAccessFile(File,String) 构造方法所指定的那样。
如果存在安全管理器,则使用 name
作为其参数调用其 checkRead
方法,以查看是否允许对该文件进行读取访问。如果该模式允许写入,那么还使用 name
作为安全管理器的参数来调用其 checkWrite
方法,以查看是否允许对该文件进行写入访问。
-
参数:
-
name
- 取决于系统的文件名 -
mode
- 此存取 mode
抛出:
-
IllegalArgumentException
- 如果此模式参数与 "r"、 "rw"、 "rws" 或 "rwd" 的其中一个不相等 -
FileNotFoundException
- 如果该模式为 "r",但给定的字符串表示一个现有的常规文件,或者该模式以 "rw" 开头,但给定的字符串不表示一个现有的可写常规文件,而且无法创建具有该名称的新常规文件,或者在打开或创建该文件时发生一些其他错误 -
SecurityException
- 如果存在安全管理器,并且其checkRead
方法拒绝对该文件的读取访问,或者该模式为 "rw",并且该安全管理器的checkWrite
方法拒绝对该文件的写入访问
使用例子:
import java.io.*;
public class UsingRandomAccessFile {
static String file = "rtest.dat";
static void display() throws IOException {
RandomAccessFile rf = new RandomAccessFile(file, "r");
for(int i = 0; i < 7; i++)
System.out.println("Value " + i + ": " + rf.readDouble());
System.out.println(rf.readUTF());
System.out.println(rf.readUTF());
rf.close();
}
public static void main(String[] args)throws IOException {
RandomAccessFile rf = new RandomAccessFile(file, "rw");
for(int i = 0; i < 7; i++)
rf.writeDouble(i*1.414);
rf.writeUTF("The end of the file");
rf.writeUTF("你好");
rf.close();
display();
rf = new RandomAccessFile(file, "rw");
rf.seek(5*8);
rf.writeDouble(47.0001);
rf.close();
display();
}
}
RandomAccessFile 不是InputStream的任何子类,它是单独的一个类,实现了DataInput和DataOutput的接口。
Using a RandomAccessFile is like using a combined DataInputStream and DataOutputStream
可以方便的处理中文字符。