本文主要是介绍粗略了解RandomAccessFile使用,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
- 明确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();}
这篇关于粗略了解RandomAccessFile使用的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!