Java篇:RandomAccessFile

 1 package ares.io;
 2 
 3 import java.io.File;
 4 import java.io.IOException;
 5 import java.io.RandomAccessFile;
 6 import java.util.Arrays;
 7 
 8 //Java文件模型操作
 9 public class RafSample {
10 
11     public static void main(String[] args) throws IOException {
12         // TODO Auto-generated method stub
13         File file = new File("rafs");
14         if (!file.exists()) {
15             file.mkdir();
16         }
17         File raf = new File(file, "raf.bat");
18         if (!raf.exists()) {
19             raf.createNewFile();
20         }
21         RandomAccessFile randomAccessFile = new RandomAccessFile(raf, "rw");
22         randomAccessFile.write('a');//只写一个字节(后八位),指针指向下一个位置
23         System.out.println(randomAccessFile.getFilePointer());//指针的位置
24         int number=0x7fffffff;
25         randomAccessFile.writeInt(number);
26         System.out.println(randomAccessFile.getFilePointer());
27         randomAccessFile.seek(0);//读取文件,将指针移到头部
28         byte[] bytes=new byte[(int)randomAccessFile.length()];
29         randomAccessFile.read(bytes);
30         System.out.println(Arrays.toString(bytes));
31         randomAccessFile.close();
32     }
33 }

 

你可能感兴趣的:(Java篇:RandomAccessFile)