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

作者:夏天de树下睡着了 时间:2023-11-28 17:40:05 

本文实例为大家分享了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();
 }

}

}

来源:http://www.cnblogs.com/wwyx-xi/p/7424660.html

标签:java,读写类,RandomAccessFile
0
投稿

猜你喜欢

  • Android自定义加载圈动画效果

    2021-07-20 14:52:23
  • 老生常谈Java异常处理和设计(推荐)

    2023-08-21 02:26:06
  • java 使用idea将工程打成jar并创建成exe文件类型执行的方法详解

    2022-12-07 02:49:30
  • Android自定义加载圈的方法

    2023-07-16 14:38:46
  • JDK8并行流及串行流区别原理详解

    2023-06-25 16:23:39
  • 死磕 java同步系列之synchronized解析

    2023-09-27 10:07:43
  • Java为实体类动态添加属性的方法详解

    2023-09-01 05:31:43
  • SpringBoot使用MyBatis-Plus解决Invalid bound statement异常

    2022-12-23 12:13:13
  • java结束进程的实例代码

    2023-11-10 14:18:38
  • JPA多数据源分布式事务处理方案

    2023-08-09 03:50:06
  • C#语言主要语言区域

    2021-10-05 13:58:38
  • mybatisPlus实现倒序拼接字符串

    2021-11-16 08:50:29
  • springboot中通过lua脚本来获取序列号的方法

    2023-05-05 04:25:44
  • Java操作Excel的示例详解

    2021-07-08 00:56:56
  • Swing图形界面实现可动态刷新的验证码

    2022-03-27 08:08:50
  • Spring JPA之find拓展方法示例详解

    2021-12-11 03:50:49
  • Java使用RedisTemplate模糊删除key操作

    2023-06-24 06:45:25
  • Java线程的start方法回调run方法的操作技巧

    2023-11-11 06:02:00
  • 关于Springboot的日志配置

    2022-12-16 10:32:33
  • Android实现登录界面记住密码的存储

    2022-11-29 04:55:44
  • asp之家 软件编程 m.aspxhome.com