/** * 随机存取流,该类支持多线程操作,可随机在文件中读取任意位置的数据,不必从头开始读取 */ public class RandomStream { public static void main(String[] args) throws IOException { RandomAccessFile randomAccessFile = new RandomAccessFile("D:\\2.txt","rw"); //设置指针的偏移位置,表示从第3个字节开始 randomAccessFile.seek(3); System.out.println("原文本长度:"+randomAccessFile.length()); String str = "随机存取流"; randomAccessFile.write(str.getBytes(StandardCharsets.UTF_8)); randomAccessFile.seek(randomAccessFile.length()); String str1 = "需要追加写的内容"; randomAccessFile.write(str1.getBytes(StandardCharsets.UTF_8)); System.out.println("追加后的文本长度:"+randomAccessFile.length()); randomAccessFile.close(); //读取上面已经写入的内容 RandomAccessFile randomAccessFile1 = new RandomAccessFile("D:\\2.txt","r"); byte[] bytes = new byte[1024]; // randomAccessFile.seek(18); randomAccessFile1.read(bytes); System.out.println(new String(bytes, StandardCharsets.UTF_8).trim()); randomAccessFile1.close(); } }
RandomAccessFile
最新推荐文章于 2022-01-14 15:40:18 发布