1、RandomAccessFile简介
随机流(RandomAccessFile)不属于IO流,支持对文件的读取和写入随机访问。
其原理是首先把随机访问的文件对象看作存储在文件系统中的一个大型 byte 数组,然后通过指向该 byte 数组的光标或索引(即:文件指针 FilePointer)在该数组任意位置读取或写入任意数据。
2、RandomAccessFile的使用
(1)创建对象
RandomAccessFile raf = new RandomAccessFile(File file, String mode);
RandomAccessFile raf = new RandomAccessFile(String name, String mode);
(2)常用方法
getFileponiter()
返回文件指针的位置seek(pos)
设置文件指针的位置
(3)mode:4种模式
- "r": 以只读的方式打开 调用write方法会抛出IOException
- "rw": 便于读取和写入
- "rws": 便于读取和写入,同时对文件的内容和元数据的更新都会同步存储
到基础存储设备 - "rwd": 便于读取和写入,同时对文件的内容的更新都会同步存储到基础存
储设备
(4)实例使用
public static void main(String[] args) {
//随机访问文件当中的某一部分数据
RandomAccessFile raf = null;
{
try {
raf = new RandomAccessFile("a.txt", "r");
//将文件指针移动到指定位置
raf.seek(500);
byte[] buf = new byte[256];
int hasRead = 0;//真实读取到的字节数 <= buf.length
while((hasRead=raf.read(buf)) > 0){
System.out.println(new String(buf, 0, hasRead));
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
raf.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
(5)练习1&2
1、随机访问文件当中的某一部分数据,打印出来500之后的数据
public static void main(String[] args) {
RandomAccessFile raf = null;
try {
raf =new RandomAccessFile("a.txt","rw");
raf.seek(500);
byte [] buffer =new byte[1024];
int temp = -1;
while ((temp=raf.read(buffer))!=-1){
System.out.println(new String(buffer,0,temp));
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
2、在指定位置追加"深圳腾讯科技有限公司"
public class TestDemo {
public static void main(String[] args) {
RandomAccessFile raf = null;
File tmp = null;
FileInputStream fis = null;
FileOutputStream fos = null;
try {
tmp = File.createTempFile("tmp", null);
raf = new RandomAccessFile("a.txt", "rw");
//需要让文件指针移动到该位置
int pos = (int) (Math.random() * raf.length());
raf.seek(pos);
//复制指定位置之后的所有内容到tmp文件中
fis = new FileInputStream(tmp);
fos = new FileOutputStream(tmp);
byte[] buf = new byte[256];
int hasRead = 0;
while ((hasRead = raf.read(buf)) > 0) {
fos.write(buf, 0, hasRead);
}
//在指定位置追加内容
raf.write("深圳腾讯科技有限公司".getBytes());
//复制tmp文件中的内容到该文件之后
while ((hasRead = fis.read(buf)) > 0) {
raf.write(buf, 0, hasRead);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
raf.close();
fis.close();
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}