- 明确RandomAccessFile的优点,可以任意位置进行读取和插入,常用于断点续传下载等场景。
- RandomAccessFile的实例化以及常用的方法函数
- 实例化RandomAccessFile 需要传入两个参数,第一个参数文件的路径path,第二个参数表示权限 “rwd”
RandomAccessFile randomAccessFile=new RandomAccessFile(f.getAbsolutePath(),"rw");
//跳过n个字节
randomAccessFile.skipBytes(n);
//读取内容
randomAccessFile.read(byte[]);
//写入内容
randomAccessFile.write(byte[]);
//叫指针移动到指定的字节位置
randomAccessFile.seek(n);
案列 :
创建一个文件 并且写入内容 “你好吗,hello word ?”
String path = Environment.getExternalStorageDirectory().getPath();
File f=new File(path,"测试.txt");
try {
if (!f.exists()){
f.createNewFile();
}
String s= "你好吗,hello word ?";
FileOutputStream fileOutputStream=new FileOutputStream(f);
fileOutputStream.write(s.getBytes());
fileOutputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
使用RandomAccessFile 在指定位置插入内容以及读取
try {
RandomAccessFile randomAccessFile=new RandomAccessFile(f.getAbsolutePath(),"rw");
String s1= "你好吗,hello word ?";
//在原有的内容之后插入内容
randomAccessFile.seek(s1.getBytes().length);
byte[] b = "单按时DNF按时DNF阿斯蒂芬".getBytes();
randomAccessFile.write(b,0,b.length);
//读取内容
RandomAccessFile randomAccessFile1=new RandomAccessFile(f.getAbsolutePath(),"rw");
byte[] bytes=new byte[1024];
// randomAccessFile.seek(6);
randomAccessFile1.read(bytes);
Log.v("===result=====","result="+new String(bytes,"utf-8"));
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}