Java核心编程之文件随机读写类RandomAccessFile详解

发布时间:2020-10-09 19:30:09 作者:夏天de树下睡着了
来源:脚本之家 阅读:144

本文实例为大家分享了Android九宫格图片展示的具体代码,供大家参考,具体内容如下

1.RandomAccessFile

  RandomAccessFile主要用于文件内容的读写访问

2.访问模式

  “r”:只读方式。

  “rw”:打开以便读取和访问,如果文件不存在则创建文件。

  “rws”: 除了‘rw‘功能以外,文件内容或者元数据更新时一同写入。

  “rwd”:除了‘rw‘功能以外,文件内容更新时一同写入。

3.使用案例

package test;

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

public class RandomAccess {
 
 
 public static void main(String[] args) {
  try {
   File file = new File("C:\\img\\666.txt");
   
   //打开文件
   RandomAccessFile randomAccess = new RandomAccessFile(file,"rwd"); //访问文件 
   Long lenth = randomAccess.length(); //获取文件长度
   System.out.println("lenth:"+lenth);
   randomAccess.seek(4); //设置指针位置
   
   //读取文件
   int c = randomAccess.read(); //读取一个字节
   System.out.println("c:"+c);
   System.out.println("c:"+(char)c); //转换为字符
   
   byte[] b = new byte[3]; //读取字节数字,创建数组
   randomAccess.read(b, 1, 2); //从指针1处读取两个字节写入数组b中
   String s = new String(b); //转换为字符串
   System.out.println("byte:"+s); //输出
   
   //写入文件
   File file2 = new File("C:\\img\\777.txt");
   if(!file2.getParentFile().exists()){
    file2.getParentFile().mkdirs();
   } 
   file2.createNewFile();
   RandomAccessFile randomAccess2 = new RandomAccessFile(file2,"rwd"); //访问文件 
   randomAccess2.write(b); //写入字符数组
   
   //关闭文件
   randomAccess.close();
   randomAccess2.close();
   
  } catch (FileNotFoundException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  } catch (IOException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  }
  
  
 }

}

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持亿速云。

推荐阅读:
  1. 小编带您Volatile的详解
  2. java _io_随机读取读入流RandomAccessFile

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

java 读写类 randomaccessfile

上一篇:Android 实现截屏功能的实例

下一篇:Serializable接口的作用_动力节点Java学院整理

相关阅读

您好,登录后才能下订单哦!

密码登录
登录注册
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》