Java中IO流 RandomAccessFile类实例详解

2025-05-29 0 96

JavaIO流 RandomAccessFile类实例详解

RandomAccessFile

  1. java提供的对文件内容的访问,既可以读文件,也可以写文件。
  2. 支持随机访问文件,可以访问文件的任意位置。
  3. java文件模型,在硬盘上的文件是byte byte byte存储的,是数据的集合
  4. 打开文件,有两种模式,“rw”读写、“r”只读;RandomAccessFile raf = new RandomAccessFile(file, "rw");,文件指针,打开文件时指针在开头 point = 0;
  5. 写方法, raf.write()–>只写一个字节(后八位),同时指针指向下一个位置,准备再次写入
  6. 读方法,int b = raf.read()–>读一个字节
  7. 文件读写完成以后一定要关闭(Oracle官方说明)

RafDemo.java

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53
package com.test.io;

import java.io.File;

import java.io.IOException;

import java.io.RandomAccessFile;

import java.util.Arrays;

public class RafDemo {

public static void main(String[] args) throws IOException {

File demo = new File("demo");

if (!demo.exists()) {

demo.mkdir();

}

File file = new File(demo, "raf.dat");

if (!file.exists()) {

file.createNewFile();

}

RandomAccessFile raf = new RandomAccessFile(file, "rw");

System.out.println(raf.getFilePointer());

raf.write('A');//一个char型占两个字节,但是write一次只写入一个字节(A字符的后八位)

System.out.println(raf.getFilePointer());

raf.write('B');

int i = 0x7fffffff;

raf.write(i >>> 24);//写入i的高八位

raf.write(i >>> 16);

raf.write(i >> 8);

raf.write(i);

System.out.println(raf.getFilePointer());

//直接写入一个int

raf.writeInt(i);

String s = "你";

byte[] b = s.getBytes("utf8");

raf.write(b);

System.out.println(raf.length());

//读文件,必须把指针移到头部

raf.seek(0);

//一次性读取,把文件中的内容都读到字节数组中

byte[] buf = new byte[(int) raf.length()];

raf.read(buf);

System.out.println(Arrays.toString(buf));

for (byte c : buf) {

System.out.print(Integer.toHexString(c & 0xff) + " ");

}

//关闭文件

raf.close();

}

}

  执行结果:

?

1

2

3

4

5

6
0

1

6

13

[65, 66, 127, -1, -1, -1, 127, -1, -1, -1, -28, -67, -96]

41 42 7f ff ff ff 7f ff ff ff e4 bd a0

感谢阅读,希望能帮助到大家,谢谢大家对本站的支持!

原文链接:http://www.cnblogs.com/tianxintian22/p/6820691.html

收藏 (0) 打赏

感谢您的支持,我会继续努力的!

打开微信/支付宝扫一扫,即可进行扫码打赏哦,分享从这里开始,精彩与您同在
点赞 (0)

声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。

快网idc优惠网 建站教程 Java中IO流 RandomAccessFile类实例详解 https://www.kuaiidc.com/116497.html

相关文章

发表评论
暂无评论