RandomAccessFile
类可以在文件中的任何位置查找或写数据。磁盘文件都是随即访问的,但是与网络套接字通信的输入/输出流却不是。打开一个随机文件,只用与读入或者同时用于读写,可以通过使用字符串r
(用于读入访问)或rw
(用于读入/写出访问)作为构造器的第二个参数来指定这个选项。
RandomAccessFile in = new RandomAccessFile("C:\\Users\\whz\\Desktop\\岗位要求.txt", "r");
RandomAccessFile inOut = new RandomAccessFile("text.txt", "rw");
随即访问文件有一个表示下一个将被读入或写出的字节所处位置的文件指针,seek
方法可以用来将这个文件指针设置到文件中的任意字节位置,seek
的参数是一个long
类型的整数,它的值位于0到文件按照字节来度量的长度之间。 getFilePointer
方法将返回文件指针的当前位置。RandomAccessFile
类同时实现了DataInput
和DataOutput
接口。为了读写随机访问文件,可以使用readInt
/writeInt
和readChar
/writeChar
之类的方法。
public static void main(String[] args) {
//默认编码
System.out.println(Charset.defaultCharset());
//获取姓名使用按UTF8编码(本人系统默认编码)还可以在()中指定编码
System.out.println("xxx".getBytes().length);
Employee[] staff = new Employee[3];
staff[0] = new Employee("xxx",1394.1,1996,6,6);
staff[1] = new Employee("xxx",2394.1,1997,6,6);
staff[2] = new Employee("xxx",3394.1,1998,6,6);
//使用wite方式将数据写入文件
try(DataOutputStream out = new DataOutputStream(new FileOutputStream("employee.dat")))
{
//保存雇员记录进入employee.dat文件
for(Employee e:staff){
out.write(e.getName().getBytes());
out.writeDouble(e.getSalary());
out.writeInt(e.getHireDay().getYear());
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e){
e.printStackTrace();
}
//使用read方式将数据从文件中读出来
try(RandomAccessFile in = new RandomAccessFile("employee.dat", "r")){
for(int i = 0 ; i < 3 ; i++){
//一个中文占了三个字节
byte[] chars = new byte[9];
in.read(chars);
String name = new String(chars,0,9);
double salary = in.readDouble();
int y = in.readInt();
System.out.println(name+" "+salary+" "+y);
}
}catch (FileNotFoundException e){
e.printStackTrace();
} catch (IOException e){
e.printStackTrace();
}
//使用·writeChars/readChar读取数据写入文件/从文件中读取数据
//按照Unicode编码,直接计算字符串中包含字符个数即可
/*try(DataOutputStream out = new DataOutputStream(new FileOutputStream("employee.dat"))) {
//保存雇员记录进入employee.dat文件
for(Employee e:staff){
out.writeChars(e.getName());
out.writeDouble(e.getSalary());
out.writeInt(e.getHireDay().getYear());
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e){
e.printStackTrace();
}
try(RandomAccessFile in = new RandomAccessFile("employee.dat", "r")){
for(int i = 0 ; i < 3 ; i++){
char[] chars = new char[3];
for(int j=0;j<3;j++){
chars[j] = in.readChar();
}
String name = new String(chars,0,3);
double salary = in.readDouble();
int y = in.readInt();
System.out.println(name+" "+salary+" "+y);
}
}catch (FileNotFoundException e){
e.printStackTrace();
} catch (IOException e){
e.printStackTrace();
}
}