IORandomAccessFile

举报
学海无涯yc 发表于 2022/07/20 18:54:48 2022/07/20
【摘要】 RandomAccessFile简要说明常用方法使用RandomAccessFile写入数据使用RandomAccessFile读取数据简要说明RandomAccessFile可以实现对文件数据的随机读取。常用方法方法描述public RandomAccessFile(File file,String mode) throws FileNotFoundException接收File类对象,设...


简要说明

RandomAccessFile可以实现对文件数据的随机读取。

常用方法

方法 描述
public RandomAccessFile(File file,String mode) throws FileNotFoundException 接收File类对象,设置时指定权限:r,w,rw
public RandomAccessFile(String name,String mode) throws FileNotFoundException 直接输入一个固定文件路径
public void close() throws IOException 关闭
public int read(byte[] b) throws IOException 将内容读取到byte数组中
public final byte readByte() throws IOException 读取一个字节
public final int readInt() throws IOException 读取整型数据
public void seek(long pos) throws IOException 设置读指针的位置
public final void writeBytes(String s) throws IOException 将一个字符串按字节的方式写入到文件中
public final void writeInt(int v) throws IOException 将一个int型数据写入文件,长度为4位
public int skipBytes(int n) throws IOException 指针跳过多少个字节

使用RandomAccessFile写入数据

 public static void main(String[] args) throws IOException {
  File file = new File("f:"+File.separator+"javaIODemo"+File.separator+"text1.txt");
  RandomAccessFile raf = new RandomAccessFile(file, "rw");//读写模式
  //保证长度一致,采用空格填充
  String names[] = new String[] {"zhangsan","lisi    ","wangwu  "};
  int ages[] = new int[] {30,20,16};
  for(int x = 0 ;x<names.length;x++) {
   raf.write(names[x].getBytes());
   raf.writeInt(ages[x]);
  }
  raf.close();
 }

使用RandomAccessFile读取数据

 public static void main(String[] args) throws IOException {
  File file = new File("f:"+File.separator+"javaIODemo"+File.separator+"text1.txt");
  RandomAccessFile raf = new RandomAccessFile(file, "rw");//读写模式
  {//读取王五的数据,字符串8位,数字4位z
   raf.skipBytes(24);
   byte[] data = new byte[8];
   int len = raf.read(data);
   System.out.println("姓名:"+new String(data,0,len).trim() +
     ",年龄:"+raf.readInt());
  }
  {//读取李四的数据,字符串8位,数字4位z
   raf.seek(12);
   byte[] data = new byte[8];
   int len = raf.read(data);
   System.out.println("姓名:"+new String(data,0,len).trim() +
     ",年龄:"+raf.readInt());
  }
  {//读取张三的数据,字符串8位,数字4位z
   raf.seek(0);
   byte[] data = new byte[8];
   int len = raf.read(data);
   System.out.println("姓名:"+new String(data,0,len).trim() +
     ",年龄:"+raf.readInt());
  }
  raf.close();
 }
【版权声明】本文为华为云社区用户原创内容,转载时必须标注文章的来源(华为云社区)、文章链接、文章作者等基本信息, 否则作者和本社区有权追究责任。如果您发现本社区中有涉嫌抄袭的内容,欢迎发送邮件进行举报,并提供相关证据,一经查实,本社区将立刻删除涉嫌侵权内容,举报邮箱: cloudbbs@huaweicloud.com
  • 点赞
  • 收藏
  • 关注作者

评论(0

0/1000
抱歉,系统识别当前为高风险访问,暂不支持该操作

全部回复

上滑加载中

设置昵称

在此一键设置昵称,即可参与社区互动!

*长度不超过10个汉字或20个英文字符,设置后3个月内不可修改。

*长度不超过10个汉字或20个英文字符,设置后3个月内不可修改。