概念
随机访问流,就是可以从文件的任何位置记性读写
随机访问流 :RandomAccessFile
public class RandomAccessFile
extends Object
implements DataOutput, DataInput, Closeable
他拥有数据访问流中的API方法
随机访问流实现两个接口 :DataOutput, DataInput
- DataOutput:提供将数据从任何Java基本类型转换为一系列字节,并将这些字节写入二进制流。 还有一种将String转换为modified UTF-8格式(这种格式会在写入的数据之前默认增加两个字节的长度)并编写结果字节系列的功能。
- DataInput:提供从二进制流读取字节并从其中重建任何Java原语类型的数据。 还有,为了重建设施String从数据modified UTF-8格式
构造方法
第二个参数的意义 mode:
操作随机访问流进行读写
public class TestRandomAccess {
public static void main(String[] args) {
String path = “E:/woniu/57/JavaSE/day19/acc.dat”;
File file = new File(path);
if(!file.exists()){
try {
file.createNewFile();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
//创建随机访问流
RandomAccessFile ran = null;
try {
ran = new RandomAccessFile(file, “rw”);
/ran.writeInt(200);
ran.writeDouble(4.1415244);
ran.writeUTF(“蜗牛学院!”);/
//读数据 按照写的顺序
int readInt = ran.readInt();
double readDouble = ran.readDouble();
String readUTF = ran.readUTF();
System.out.println(readInt + “—“+readDouble + “—“+readUTF);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally {
if(ran != null){
try {
ran.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
}
从文件的任何的位置进行读写
方法 | 意义 |
---|---|
public long getFilePointer() throws IOException | 返回此文件中的当前偏移量 |
public void seek(long pos) throws IOException | 设置文件指针偏移,从该文件的开头偏移,发生下一次读取或写入 |
public class TestRandomSeek {
public static void main(String[] args) {
String path = “E:/woniu/57/JavaSE/day19/Hello.java”;
File file = new File(path);
RandomAccessFile ran = null;
try {
ran = new RandomAccessFile(file, “rw”);
ran.seek(100L); //设置偏移量
//long l = ran.getPointFile(); //获取偏移量
/int i = ran.read();
while(i!=-1){
System.out.print((char)i);
i = ran.read();
}/
String s = “abccdddfgfdgdgdffg”;
ran.writeUTF(s);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally {
if(ran != null){
try {
ran.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
}