Java RandomAccessFile基本的用法

一、认识RandomAccessFile类

      RandomAccessFile是Java提供的对文件内容的访问,既能够读取文件,也能够写文件;

      RandomAccessFile支持随机访问文件,可以访问文件的任意位置。

(1)打开文件,有两种打开模式-----“rw”(读写)、“r”(只读)

       RandomAccessFile raf=new RandomAccessFile(file,“rw”);

RandomAccessFile能够随机读取文件的内容是因为存在一个指针,记录读取或者写入的位置,打开文件是pointer=0;

Ran

(2)写方法

  写方法一次只能写入一个字节,写入后指针指向下一个位置

    raf.write(int);//斜土的是int的后8位

(3)读方法

同样的读方法也是一次读取一个字节

int b=raf.read();

(4)文件读写完成后要关闭

raf.close();

简单操作

package com.neuedu.demo01;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.util.Arrays;

public class RandomAccessFiledemo {
    public static void main(String[] args)throws IOException {
     File demo=new File("demo");
     if (!demo.exists()) {
         demo.mkdir();
     }
     File file=new File(demo,"raf.bat");
     if (!file.exists()) {
         file.createNewFile();
     }
     RandomAccessFile raf=new RandomAccessFile(file, "rw");
    
     System.out.println("向文件中写入");
     raf.write('A');   //写入一个字符,只会写入第八位
     raf.write('B');
     int i=112324;
     //用write方法每次只能写一个字节,如果要把i写进去需要写4次
     raf.write(i>>>24);
     raf.write(i>>>16);
     raf.write(i>>>8);
     raf.write(i);
     raf.writeInt(i);                         //也可以直接写入一个整数,占4个字节,底层实现就是上面的方法
     raf.writeUTF("这是一个UTF字符串");         // 这个长度写在当前文件指针的前两个字节处,可用readShort()读取 
     raf.writeDouble(8.236598);               // 占8个字节 
     raf.writeBoolean(true);                  // 占1个字节 
     raf.writeShort(395);                     // 占2个字节 
     raf.writeLong(2325451l);                 // 占8个字节 
     raf.writeFloat(35.5f);                   // 占4个字节 
     raf.writeChar('a');                      // 占2个字节 
     String string="中";
     byte [] by=string.getBytes();
     raf.write(by);
     System.out.println(raf.getFilePointer());
    
    
    
     //读取文件,把指针移到读取的位置---利用的是seek()
     raf.seek(0);                                                 ///将指针移到文件的开头
     //一次性读取,就是把文件中的内容都读取到字节数组中
     byte [] buffer=new byte[(int)raf.length()];
     raf.read(buffer);   
     //将文件一次性读取到字节数组中
     System.out.println("输出文件全部内容:");
     System.out.println(Arrays.toString(buffer));
     for (byte b : buffer) {
         System.out.print(Integer.toHexString(b &0xff)+" ");      //以十六进制输出
     }
     System.out.println();
     raf.seek(2);                                                //将指针移到第三个字节位置
     int readInt = raf.readInt();                                //读取一个整数
     System.out.println(readInt);
     raf.skipBytes(4);                                           //跳过一个int
     System.out.println(raf.readUTF());                          //输出UTF语句
    
    
    }

}

原文地址:https://www.cnblogs.com/Actexpler-S/p/7581924.html