当前位置:Gxlcms > 数据库问题 > RandomAccessFile--随机访问文件

RandomAccessFile--随机访问文件

时间:2021-07-01 10:21:17 帮助过:15人阅读

java.io.FileNotFoundException; import java.io.IOException; import java.io.RandomAccessFile; public class RandomAccessFileDemo { public static void main(String[] args) throws IOException { /* * RandomAccessFile * 特点: * 1.只能操作文件 * 2.既能读,有能写 * 3.维护了一个byte数组,内部定义了字节流的读取和写入 */ // writeFile(); readFile(); } public static void readFile() throws IOException { RandomAccessFile raf = new RandomAccessFile("tempfile\\random.txt","r"); //随机读取,只要通过设置指针的位置即可 raf.seek(8); byte[] buf = new byte[4]; raf.read(buf); String name = new String(buf); int age = raf.readInt(); System.out.println(name+":"+age); raf.close(); } public static void writeFile() throws IOException { //1.创建一个随机访问文件的对象 //文件不存在,则创建,存在,则不创建不覆盖 RandomAccessFile raf = new RandomAccessFile("tempfile\\random.txt","rw"); //2.写入姓名和年龄 // raf.write("张三".getBytes()); // raf.writeInt(97);//保证整数的字节原样完整性 // raf.write("李四".getBytes()); // raf.writeInt(99);//保证整数的字节原样完整性 //3.随机写入 raf.seek(8);//设置指针的位置,可以随时修改文件里面的数据 raf.write("王五".getBytes()); raf.writeInt(100); System.out.println(raf.getFilePointer()); //随机访问时希望数据有点规律 raf.close(); } }

 

RandomAccessFile--随机访问文件

标签:

人气教程排行