Java字节流入门(文件流)

版权声明:转载请注明出处 https://blog.csdn.net/qiaojialin/article/details/81031422

导读

在编程语言的教材中,文件流大多是放在最后一章介绍的,而且大学不怎么考流,所以没有重视过。在开始学习 java 流时,发现大多博客上来就放一大家子类图,每次看到都头大。

在数据库领域,不可避免会接触到文件和流,而且磁盘上的文件组织是一件很有意思的事。因此,通过对实际项目中的流使用方式进行研究,加上网上博客学习,发现流也可以快速入门。

本系列教程的目标是从最简单的入手,一步步入门 java 字节流。

我们从文件流入手,先介绍两类文件流,都是字节流:

顺序文件字节流:FileOutputstream、FileInputStream

随机文件字节流:RandomAccessFile。

至于为什么只介绍字节流,因为字节流高效,在文件格式领域应用最广。字节就是byte。

FileOutputStream

import java.io.*;
import java.nio.file.Path;
import java.nio.file.Paths;

public class FileIOStreamTest {

    private static final Path path = Paths.get("src", "main", "resources", "test.myfile");
    private static final File file = path.toFile();

    public static void main(String[] args) throws IOException {
        if (file.exists())
            file.delete();

        //覆盖写入 6 个字节
        write(new byte[]{1, 2, 3, 4, 5, 6}, false);

        //FileInputStream只能顺序读
        InputStream in = new FileInputStream(file);

        byte[] array = new byte[3];
        //读三个字节并打印
        in.read(array);  print(array);
        System.out.println("\n还剩 " + in.available() + " 个字节可读");

        //再读三个字节并打印
        in.read(array);  print(array);
        System.out.println("\n没得读了:" + in.available());

        //覆盖写入 2 个字节
        write(new byte[]{7, 8}, false);
        read();
        //追加写入 3 个字节
        write(new byte[]{1, 2, 3}, true);
        read();
    }

    private static void print(byte[] array) {
        for (byte b : array) {
            System.out.print(b);
        }
    }

    //将字节数组 a 以 mode 模式写入文件
    private static void write(byte[] a, boolean mode) {
        try (OutputStream out = new FileOutputStream(file, mode)) {
            out.write(a);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    //读取 10 个字节
    public static void read() {
        try (InputStream in = new FileInputStream(file)) {
            byte[] a = new byte[10];
            System.out.print("整个文件有 " + in.available() + " 个字节:");
            in.read(a);
            for (int i = 0; i < a.length; i++) {
                System.out.print(a[i]);
            }
            System.out.println();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}

运行结果

123
还剩 3 个字节可读
456
没得读了:0
整个文件有 2 个字节:7800000000
整个文件有 5 个字节:7812300000

RandomAccessFile

重点:随机,有一个独特的seek方法,可以跳到距离文件头任意的位置,想读哪里读哪里,读完还可以从头来过继续读。

RandomAccessFile :既可以随机读,也可以随机写,在初始化时候设置模式:rw等。由于很好的灵活性,大部分大数据的文件格式的读取都用的这种方式。

import java.io.File;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.nio.file.Path;
import java.nio.file.Paths;

public class RandomAccessFileTest {

    private static final Path path = Paths.get("src", "main", "resources", "test.myfile");
    private static final File file = path.toFile();

    public static void main(String[] args) throws IOException {
        byte[] a = new byte[10];
        RandomAccessFile randomAccess = new RandomAccessFile(file, "rw");
        //跳过 2 个字节
        randomAccess.seek(2);
        //写入 6 个字节
        randomAccess.write(new byte[]{1,2,3,4,5,6});
        System.out.println("当前位置: " + randomAccess.getFilePointer());
        System.out.println("文件长度: "+randomAccess.length());

        //从头读取 10 个 bytes
        randomAccess.seek(0);
        randomAccess.read(a);
        print(a);

        //移动到 offset=3 的位置
        randomAccess.seek(3);
        System.out.println("当前位置: " + randomAccess.getFilePointer());
        //写入一个byte,直接覆盖原来的数据
        randomAccess.write(new byte[]{7});

        //从头读取 10 个 bytes
        randomAccess.seek(0);
        randomAccess.read(a);
        print(a);

        //seek 到 offset=2 处
        randomAccess.seek(2);
        a = new byte[3];
        //读 2 个字节到 a
        randomAccess.read(a, 0, 2);
        print(a);

        randomAccess.close();
        file.delete();
    }


    private static void print(byte[] array) {
        System.out.print("读取:");
        for (byte b : array) {
            System.out.print(b);
        }
        System.out.println();
    }
}

输出:

当前位置: 8
文件长度: 8
读取:7812345600
当前位置: 3
读取:7817345600
读取:170

这两中文件流很直观,区别也很明显,一个顺序读写,一个随机读写。

欢迎关注个人公众号:数据库漫游指南

这里写图片描述

猜你喜欢

转载自blog.csdn.net/qiaojialin/article/details/81031422