0
点赞
收藏
分享

微信扫一扫

Java:RandomAccessFile随机访问文件


构造方法

RandomAccessFile(File file, String mode)

RandomAccessFile(String name, String mode)

mode取值

模式

作用

r

表示以只读方式打开,调用结果对象的任何write方法都将导致抛出IOException

rw

打开以便读取和写入,如果该文件尚不存在,则尝试创建该文件

rws

打开以便读取和写入,相对于"rw",还要求对文件内容或元数据的每个更新都同步写入到底层存储设备

rwd

打开以便读取和写入,相对于"rw",还要求对文件内容的每个更新都同步写入到底层存储设备

中文字符和英文字符的长度

  • 一个中文字符占3个字节的长度
  • 一个英文字符占1个字节的长度

System.out.println("你好".getBytes().length);
// 6

System.out.println("Java".getBytes().length);
// 4

先写入一段文本

package com.example.demo;

import java.io.IOException;
import java.io.RandomAccessFile;

public class Demo {
public static void main(String[] args) throws IOException {
// 写入中文和英文字符
RandomAccessFile randomAccessFile = new RandomAccessFile("demo.txt", "rw");
randomAccessFile.write("你好,Java".getBytes());
randomAccessFile.close();
}
}

移动文件指针到指定位置

package com.example.demo;

import java.io.IOException;
import java.io.RandomAccessFile;

public class Demo {
public static void main(String[] args) throws IOException {
// 将Java替换成World,从第三个中文字符开始
RandomAccessFile randomAccessFile = new RandomAccessFile("demo.txt", "rw");
// 3个中文字符长度是 9 = 3 * 3
randomAccessFile.seek(9);
randomAccessFile.write("World".getBytes());
}
}

最终输出结果

你好,World

参考
​RandomAccessFile​​RandomAccessFile详解


举报

相关推荐

0 条评论