随机流RandomAccessFile的用法及随机流与IO缓冲流的效率对比

158 阅读2分钟

本文已参与「新人创作礼」活动,一起开启掘金创作之路。

随机流从字面上的意思就是随机,顾名思义,他就是可以从文件的任何地方开始写数据,可以覆盖原有的数据,也可用从中间插入,用法灵活。下面我来介绍一下他的用法。

随机流和IO流的原理是不同的。随机流的优点就是可以随意从指定的位置读取文件。

IO流:字节流:FileInputStream和FileOutputStream

       字节缓冲流:BufferedInputStream和BufferedOutputStream(对字节流进行封装)

       字符流:FileReader和FileWriter

随机流:RandomAccessFile(既可以读也可以写,可用多线程上传、下载)的优点是可以从指定位置读,指定位置写的一个类,多用于多线程下载一个大文件。

常用构造方法:RandomAccessFile ra_read = newRandomAccessFile(File file, String mode);

参数 mode 的值可选 "r":可读,"w" :可写,"rw":可读性;

成员方法:

            将指针移动到某个位置开始读写: void seek(int index)

            给写入文件预留空间:setLength(long len)

            读取一行:String readLine()

            跳过字节:int skipBytes(int n)

下面我们介绍随机流的用法:

1.普通单独使用:RandomAccessFile

单独使用RandomAccessFile和io缓冲流效率对比

public class TestRoundomFile { public static void main(String[] args) throws IOException { long start = System.currentTimeMillis(); // 调用普通io缓冲流 // testIO(); // 调用随机流 testRandomAccessFile(); long end = System.currentTimeMillis(); System.out.println("2.6G文件复制所用时间 : " + (end - start)); /** * 调用普通io缓冲流时,打印结果为--2.6G文件复制所用时间 : 14443ms * 调用随机流时,打印结果为--2.6G文件复制所用时间 : 22091ms */ }

private static void testRandomAccessFile() throws IOException {
    RandomAccessFile ra_read = new RandomAccessFile("d:/TEST/testfile.zip", "r");
    RandomAccessFile ra_desc = new RandomAccessFile("d:/TEST/testfile-copy.zip", "rw");
    // 源和目的都从0开始(可随意跳)
    ra_read.seek(0);
    ra_desc.seek(0);

    byte[] bys = new byte[1024];
    int len;
    while ((len = ra_read.read(bys)) != -1) {
        ra_desc.write(bys, 0, len);
    }
    ra_read.close();
    ra_desc.close();
}

private static void testIO() throws IOException {
    // 传参要是对应的流,缓冲流底层默认一次8192数组
    BufferedInputStream bis = new BufferedInputStream(
            new FileInputStream("d:/TEST/testfile.zip"));
    BufferedOutputStream bos = new BufferedOutputStream(
            new FileOutputStream("d:/TEST/testfile-COPY.zip"));
    byte[] bys = new byte[1024];
    int len;
    while ((len = bis.read(bys)) != -1) {
        bos.write(bys, 0, len);
    }
    bis.close();
    bos.close();
}

} 通过对比RandomAccessFile不使用多线程的情况下,效率低于io缓冲流