分享

RandomAccessFile使用小结

 大明明小珠珠 2018-12-11

本文是基于Linux环境运行,读者阅读前需要具备一定Linux知识

RandomAccessFile是Java输入/输出流体系中功能最丰富的文件内容访问类,既可以读取文件内容,也可以向文件输出数据。与普通的输入/输出流不同的是,RandomAccessFile支持跳到文件任意位置读写数据,RandomAccessFile对象包含一个记录指针,用以标识当前读写处的位置,当程序创建一个新的RandomAccessFile对象时,该对象的文件记录指针对于文件头(也就是0处),当读写n个字节后,文件记录指针将会向后移动n个字节。除此之外,RandomAccessFile可以自由移动该记录指针

RandomAccessFile包含两个方法来操作文件记录指针:

  • long getFilePointer():返回文件记录指针的当前位置
  • void seek(long pos):将文件记录指针定位到pos位置

RandomAccessFile类在创建对象时,除了指定文件本身,还需要指定一个mode参数,该参数指定RandomAccessFile的访问模式,该参数有如下四个值:

  • r:以只读方式打开指定文件。如果试图对该RandomAccessFile指定的文件执行写入方法则会抛出IOException
  • rw:以读取、写入方式打开指定文件。如果该文件不存在,则尝试创建文件
  • rws:以读取、写入方式打开指定文件。相对于rw模式,还要求对文件的内容或元数据的每个更新都同步写入到底层存储设备,默认情形下(rw模式下),是使用buffer的,只有cache满的或者使用RandomAccessFile.close()关闭流的时候儿才真正的写到文件
  • rwd:与rws类似,只是仅对文件的内容同步更新到磁盘,而不修改文件的元数据

代码1-1

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
import java.io.IOException;
import java.io.RandomAccessFile;
public class RandomAccessRead {
    public static void main(String[] args) {
        if (args == null || args.length == 0) {
            throw new RuntimeException("请输入路径");
        }
        RandomAccessFile raf = null;
        try {
            raf = new RandomAccessFile(args[0], "r");
            System.out.println("RandomAccessFile的文件指针初始位置:" + raf.getFilePointer());
            raf.seek(100);
            byte[] bbuf = new byte[1024];
            int hasRead = 0;
            while ((hasRead = raf.read(bbuf)) > 0) {
                System.out.print(new String(bbuf, 0, hasRead));
            }
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } finally {
            try {
                if (raf != null) {
                    raf.close();
                }
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    }
}

 

代码1-1运行结果:

1
2
3
4
5
6
7
8
9
10
11
12
13
root@lejian:/home/software/.io# cat article
Unexpected Benefits of Drinking Hot Water
Reasons To Love An Empowered Woman
Reasons Why It’s Alright To Feel Lost In A Relationship
Signs You’re Uber Smart Even If You Don’t Appear to Be
Differences Between Positive People And Negative People
Sex Before Marriage: 5 Reasons Every Couple Should Do It
root@lejian:/home/software/.io# java RandomAccessRead article
RandomAccessFile的文件指针初始位置:0
ght To Feel Lost In A Relationship
Signs You’re Uber Smart Even If You Don’t Appear to Be
Differences Between Positive People And Negative People
Sex Before Marriage: 5 Reasons Every Couple Should Do It

 

代码1-2使用RandomAccessFile来追加文件内容,RandomAccessFile先获取文件的长度,再将指针移到文件的末尾,再将要插入的内容插入到文件

代码1-2

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
import java.io.IOException;
import java.io.RandomAccessFile;
public class RandomAccessWrite {
    public static void main(String[] args) {
        if (args == null || args.length == 0) {
            throw new RuntimeException("请输入路径");
        }
        RandomAccessFile raf = null;
        try {
            String[] arrays = new String[] { "Hello Hadoop", "Hello Spark", "Hello Hive" };
            raf = new RandomAccessFile(args[0], "rw");
            raf.seek(raf.length());
            raf.write("追加内容:\n".getBytes());
            for (String arr : arrays) {
                raf.write((arr + "\n").getBytes());
            }
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } finally {
            try {
                if (raf != null) {
                    raf.close();
                }
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    }
}

 

代码1-2运行结果:

1
2
3
4
5
6
7
8
9
10
11
12
13
root@lejian:/home/software/.io# cat text
Hello spring
Hello Hibernate
Hello Mybatis
root@lejian:/home/software/.io# java RandomAccessWrite text
root@lejian:/home/software/.io# cat text
Hello spring
Hello Hibernate
Hello Mybatis
追加内容:
Hello Hadoop
Hello Spark
Hello Hive

 

RandomAccessFile如果向文件的指定的位置插入内容,则新输出的内容会覆盖文件中原有的内容。如果需要向指定位置插入内容,程序需要先把插入点后面的内容读入缓冲区,等把需要的插入数据写入文件后,再将缓冲区的内容追加到文件后面,代码1-3为在文件指定位置插入内容

代码1-3

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
54
55
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.RandomAccessFile;
public class InsertContent {
    public static void main(String[] args) {
        if (args == null || args.length != 3) {
            throw new RuntimeException("请分别输入操作文件、插入位置和插入内容");
        }
        FileInputStream fis = null;
        FileOutputStream fos = null;
        RandomAccessFile raf = null;
        try {
            raf = new RandomAccessFile(args[0], "rw");
            File tmp = File.createTempFile("tmp", null);
            tmp.deleteOnExit();
            fis = new FileInputStream(tmp);
            fos = new FileOutputStream(tmp);
            raf.seek(Long.parseLong(args[1]));
            byte[] bbuf = new byte[64];
            int hasRead = 0;
            while ((hasRead = raf.read(bbuf)) > 0) {
                fos.write(bbuf, 0, hasRead);
            }
            raf.seek(Long.parseLong(args[1]));
            raf.write("\n插入内容:\n".getBytes());
            raf.write((args[2] + "\n").getBytes());
            while ((hasRead = fis.read(bbuf)) > 0) {
                raf.write(bbuf, 0, hasRead);
            }
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } finally {
            try {
                if (fis != null) {
                    fis.close();
                }
                if (fos != null) {
                    fos.close();
                }
                if (raf != null) {
                    raf.close();
                }
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    }
}

 

代码1-3运行结果:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
root@lejian:/home/software/.io# cat text
To love oneself is the beginning of a lifelong romance.
Change your life today. Don't gamble on the future, act now, without delay.
Health is the thing that makes you feel that now is the best time of the year.
The very essence of romance is uncertainty.
Your time is limited, so don’t waste it living someone else’s life.
root@lejian:/home/software/.io# java InsertContent text 100 "Success covers a multitude of blunders."
root@lejian:/home/software/.io# cat text
To love oneself is the beginning of a lifelong romance.
Change your life today. Don't gamble on the
插入内容:
Success covers a multitude of blunders.
future, act now, without delay.
Health is the thing that makes you feel that now is the best time of the year.
The very essence of romance is uncertainty.
Your time is limited, so don’t waste it living someone else’s life.

 

    本站是提供个人知识管理的网络存储空间,所有内容均由用户发布,不代表本站观点。请注意甄别内容中的联系方式、诱导购买等信息,谨防诈骗。如发现有害或侵权内容,请点击一键举报。
    转藏 分享 献花(0

    0条评论

    发表

    请遵守用户 评论公约

    类似文章 更多