🔥码云GVP开源项目 12k star Uniapp+ElementUI 功能强大 支持多语言、二开方便! 广告
# RandomAccessFile > ## 基本操作 - 创建对象 ``` /** * file 为io.File类型 * mode 为模式为String类型,选择模式,可选'r','w','rw'等模式对应‘读’,‘写’,‘读写’权限, * **/ new RandomAccessFile(file, mode) ``` - 查看长度(字节) ``` RandomAccessFile对象.length(); // 显示RandomAccessFile对象文本的字节长度 ``` - 查看当前指针位置(字节) ``` RandomAccessFile对象.getFilePointer(); // 显示当前指针指向文本字节位置 ``` - 设置指针位置(字节) ``` RandomAccessFile对象.seek(Long point) // 设置指针为long类型,指向文本具体字节数据 ``` - 字符流读写 ``` RandomAccessFile对象.readChar(); RandomAccessFile对象.writeChars(s); // s为String类型的写入内容 ``` - 字节流读写 ``` RandomAccessFile对象.read(obj,begin,end); // obj为byte数组对象,begin为开始位置,end为结束位置 RandomAccessFile对象.write(b); // b 为byte类型的写入内容 ``` * [ ] 注意 write() 方法 该方法会从指定位置开始覆盖写入内容,并保持覆盖前后文件大小一致, 例如 ABCD 从2的位置写入 FF后结果为 AFFD; > ## 应用 - 向指定文件追加内容(在文件末尾追加) ``` /* * RandomAccessFile 向指定文件追加内容(在文件末尾追加) */ public void appendTest(String url) { File file = new File(url); String permision = "rw"; try { if (!file.exists()) { File parentFile = file.getParentFile(); if (parentFile.mkdirs()) { file.createNewFile(); } } RandomAccessFile raf = new RandomAccessFile(file, permision); raf.seek(raf.length()); System.out.println("raf.length:" + raf.length()); System.out.println("raf.getFilePointer:" + raf.getFilePointer()); String value = "這是追加內容!" + "\r\n"; raf.write(value.getBytes("utf-8")); } catch (Exception e) { e.printStackTrace(); } } ``` - 从指定位置读取内容 ``` /* * RandomAccessFile 从指定位置读取内容 */ public void readTest(String url) { File file = new File(url); try { RandomAccessFile raf = new RandomAccessFile(file, "r"); raf.seek(20);// 设置指针位置 byte[] temp = new byte[1024]; int read = -1; while ((read = raf.read(temp)) != -1) { System.out.println(new String(temp, 0, read)); } raf.close(); } catch (Exception e) { e.printStackTrace(); } } ``` - 从指定位置插入指定的内容 ``` /* * RandomAccessFile 从指定位置插入指定的内容 注意: raf.write() * 该方法会从指定位置开始覆盖写入内容,并保持覆盖前后文件大小一致, 例如 ABCD 从2的位置写入 FF后结果为 AFFD; * 特别注意的是2是字节大小,所以当有中文字体被覆盖时,可能使字体遭到破坏 * * 因此要从指定位置插入指定的内容办法解决办法是: * 1 先把指定位置后边的内容写入到一个临时文件中; * 2 然后在指定位置插入指定内容; * 3 最后写入临时数据; */ public void insertTest(String url) { try { File file = new File(url); File tempFile = File.createTempFile("tmp", null); //创建临时文件 FileInputStream fileInputStream = new FileInputStream(tempFile); FileOutputStream fileOutputStream = new FileOutputStream(tempFile); RandomAccessFile raf = new RandomAccessFile(file, "rw"); raf.seek(20); byte []buf = new byte[1024]; int read = -1; while((read = raf.read(buf)) != -1) { //要插入的内容的地方后面内容写入临时文件 fileOutputStream.write(buf, 0, read); } raf.seek(20); //指针重新指到要插入的地方 String value = "插入de内容!!"+"\r\n"; raf.write(value.getBytes("UTF-8")); //插入内容 while((read = fileInputStream.read(buf)) != -1) { //插入临时文件数据 raf.write(buf,0,read); } fileOutputStream.close(); fileInputStream.close(); raf.close(); } catch (Exception e) { e.printStackTrace(); } } ```