RandomAccessFile类的使用
File类只用于表示文件(目录)的信息(名称、大小等),不能用于文件内容的访问
RandomAccessFile java提供的对文件内容的访问,既可以读文件,也可以写文件。
RandomAccessFile支持随机访问文件,可以访问文件的任意位置
(1)java文件模型
在硬盘上的文件是byte byte byte存储的,是数据的集合
(2)打开文件
有两种模式“rw”(读写)“r”(只读)
1 RandomAccessFile raf = new RandomAccessFile(file,“rw”)
(3)写方法
raf.write(int) --->只写一个字节(后8位) ,同时指针指向下一个位置,准备再次写入
(4)读方法
int b = raf.read() --->读一个字节
(5)文件读写完成以后一定要关闭(Oracle官方说明)
1 import java.io.File;
2 import java.io.IOException;
3 import java.io.RandomAccessFile;
4 import java.util.Arrays;
5
6 public class RafDemo {
7
8 /**
9 * @param args
10 */
11 public static void main(String[] args) throws IOException{
12 File demo = new File("demo");
13 if(!demo.exists())
14 demo.mkdir();
15 File file = new File(demo,"raf.dat");
16 if(!file.exists())
17 file.createNewFile();
18
19 RandomAccessFile raf = new RandomAccessFile(file, "rw");
20 //指针的位置
21 System.out.println(raf.getFilePointer());
22
23 raf.write('A');//只写了一个字节
24 System.out.println(raf.getFilePointer());
25 raf.write('B');
26
27 int i = 0x7fffffff;
28 //用write方法每次只能写一个字节,如果要把i写进去就得写4次
29 raf.write(i >>> 24);//高8位
30 raf.write(i >>> 16);
31 raf.write(i >>> 8);
32 raf.write(i);
33 System.out.println(raf.getFilePointer());
34
35 //可以直接写一个int
36 raf.writeInt(i);
37
38 String s = "中";
39 byte[] gbk = s.getBytes("gbk");
40 raf.write(gbk);
41 System.out.println(raf.length());
42
43 //读文件,必须把指针移到头部
44 raf.seek(0);
45 //一次性读取,把文件中的内容都读到字节数组中
46 byte[] buf = new byte[(int)raf.length()];
47 raf.read(buf);
48
49 System.out.println(Arrays.toString(buf));
50 for (byte b : buf) {
51 System.out.println(Integer.toHexString(b & 0xff)+" ");
52 }
53 raf.close();
54 }
55
56 }