Java之文件的随机访问和读写RandomAccessFile

时间:2022-12-26 17:11:42
 1 package FileDemo;
 2 
 3 import java.io.IOException;
 4 import java.io.RandomAccessFile;
 5 
 6 public class RandomAccessFileDemo {
 7 
 8     /**
 9      * @param args
10      * @throws IOException
11      */
12     public static void main(String[] args) throws IOException {
13 
14         writeAccess();
15         readAccess();
16         randomWrite();
17     }
18 
19     // 随机写入数据,可以实现对已有数据的修改,因为可以使用seek()方法改变文件指针的位置
20     private static void randomWrite() throws IOException {
21         RandomAccessFile raf = new RandomAccessFile("random.txt", "rw");
22         raf.seek(8 * 4);//将文件指针移动到指定位置
23         System.out.println(raf.getFilePointer());
24         raf.write("Ruby".getBytes());
25         raf.writeInt(99);
26     }
27 
28     private static void readAccess() throws IOException {
29         RandomAccessFile raf = new RandomAccessFile("random.txt", "r");
30         System.out.println(raf.getFilePointer());
31         raf.seek(8);// 用于实现随机读取文件中的数据,数据最号有规律
32         System.out.println(raf.getFilePointer());
33         byte buf[] = new byte[4];
34         raf.read(buf);
35         String name = new String(buf);
36         int age = raf.readInt();
37         System.out.println("name=" + name);
38         System.out.println("age=" + age);
39         System.out.println(raf.getFilePointer());
40 
41     }
42 
43     private static void writeAccess() throws IOException {
44         // rw:当这个文件不存在,会创建文件,当文件已经存在,不会创建,所以不会出现和输出流一样的覆盖
45         RandomAccessFile raf = new RandomAccessFile("random.txt", "rw");
46         raf.write("Java".getBytes());
47         raf.writeInt(97);
48         raf.write("python".getBytes());
49         raf.write(98);
50         raf.close();
51     }
52 
53 }