当前位置: 首页 > 图灵资讯 > 技术篇> 10、FileInputStream和RandomAccessFile的源码分析和使用方法详细分析(windows操作系统,JDK8)

10、FileInputStream和RandomAccessFile的源码分析和使用方法详细分析(windows操作系统,JDK8)

来源:图灵教育
时间:2026-04-27 09:02:35
一、FileinputStream源码分析及使用方法详细分析

  FileInputStream 是 Java IO 通过封装操作系统的文件操作,系统中文件读取的基本类提供了简单易用的字节流读取界面。其设计融合了模板方法模式(统一接口)、适配器模式(屏蔽系统差异)和代理模式(资源生命周期管理)是面向对象设计原则的典型实践   FileInputStream 适用于读取二进制文件,如图片、音频、视频等非文本文件(建议使用字符文件) FileReader)。FileInputStream 在操作文件时,需要与Filedescriptor(文件操作符)相关联。关于Filedescriptor(文件操作符),可以查看我的另一个博客:5、Filedescriptor源代码及使用注意事项(windows操作系统,JDK8) FileInputStream.class::getChannel() 函数可以将当前的FileinputStream对象与NIO中的FileChanel联系起来,从而获得更高效的文件操作(如内存映射、分散/聚集读取)。   使用FileInputStream后,必须进行显式调用 close() 函数释放文件句柄(或使用) try-with-resources 自动关闭),避免资源泄漏。FileinputStream不是线程安全的。在多线程下使用FileinputStream时,应注意线程安全。   FileinputStreamUML关系图如下: clipboard

  FileInputStream.class的源码如下

import java.nio.channels.FileChannel;
import sun.nio.ch.FileChannelImpl;
public
class FileInputStream extends InputStream
{
    //文件描述符
    private final FileDescriptor fd;
    //在构造函数中,通过File对象获取文件的路径
    private final String path;
    ///NIO中的FileChanel可以在getChanel()中更有效地操作文件 将当前FileinputStream对象与FileChanel相关联
    private FileChannel channel = null;
    ///在close()函数中(关闭当前Fileinputstream的函数),用于线程同步的锁对象
    private final Object closeLock = new Object();
    private volatile boolean closed = false;///目前FileinputStream是否关闭标记
    
    //构造函数,入参是文件的路径名,例如在windows操作系统D盘下的nio_data.txt文件路径时,入参为"D:\nio_data.txt"
    public FileInputStream(String name) throws FileNotFoundException {
        this(name != null ?= null ? new File(name) : null);///当FileinputStream对象通过文件的路径名构建时,文件的路径名最终应构建为File对象
    }
    
    //构造函数,FileInputStream对象通过File对象构建
    public FileInputStream(File file) throws FileNotFoundException {
        String name = (file != null ? file.getPath() : null);
        SecurityManager security = System.getSecurityManager();
        if (security != null) {
            security.checkRead(name);  // 阅读权限检查(防止未经授权的文件读取当前线程)
        }
        if (name == null) {
            throw new NullPointerException();//文件的路径名==null,抛出Nullpointerexception
        }
        if (file.isInvalid()) {
            throw new FileNotFoundException("Invalid file path");isinvalid()函数返回true时//File对象,抛出FilenotFoundexception
        }
        fd = new FileDescriptor();
        fd.attach(this);// 绑定当前FileinputStream和文件描述符(用于资源回收)
        path = name;
        open(name);// 最终调用本地函数(native修改)open0()打开文件
    }
    //构造函数,Fileinputstream对象通过Filedescriptor对象构建
    public FileInputStream(FileDescriptor fdObj) {
        SecurityManager security = System.getSecurityManager();
        if (fdObj == null) {
            throw new NullPointerException();
        }
        if (security != null) {
            security.checkRead(fdObj);// 阅读权限检查(防止未经授权的文件读取当前线程)
        }
        fd = fdObj;
        path = null;

        /*
         * FileDescriptor is being shared by streams.
         * Register this stream with FileDescriptor tracker.
         */
        fd.attach(this);// 绑定当前FileinputStream和文件描述符(用于资源回收)
    }
    ///native修改的本地函数,目前,FileinputStream对象为后续的read()函数打开指定文件readBytes()函数、skip()准备函数
    private native void open0(String name) throws FileNotFoundException;

    private void open(String name) throws FileNotFoundException {
        open0(name);
    }
    
    public int read() throws IOException {
        return read0();
    }
    ///native修改的本地函数,目前,FileinputStream对象每次从指定文件中读取一个字节;
    ///如果您没有读取文件的末尾,请返回读取字节的ASCII编码。如果您已经读取了文件的末尾,请返回-1
    private native int read0() throws IOException;
    ///native修改的本地函数,目前这个FileinputStream对象每次从一个指定文件读取len字节到byteam b[]数组的[off,off+len)索引位置;
    ///如果没有读取文件的末尾,返回已读取的byte b[]数组中累计字节的数量(所有累计读取的字节都是通过ASCII编码的)。如果该文件已读取,则返回-1
    private native int readBytes(byte b[], int off, int len) throws IOException;

    public int read(byte b[]) throws IOException {
        return readBytes(b, 0, b.length);
    }

    public int read(byte b[], int off, int len) throws IOException {
        return readBytes(b, off, len);
    }

    public long skip(long n) throws IOException {
        return skip0(n);
    }
    通过这个函数,//native修改的本地函数,目前,FileinputStream对象可以从指定文件跳过n个字节进行后续操作(例如通过read()函数读取)
    private native long skip0(long n) throws IOException;
    
    public int available() throws IOException {
        return available0();
    }
    ///native修改的本地函数,返回与当前FileinputStream对象相关的指定文件也可以进行后续操作(如read()函数和skip()函数)字节数
    private native int available0() throws IOException;
    
    public void close() throws IOException {
        synchronized (closeLock) {// 通过synchronized 防止多线程重复关闭
            if (closed) {
                return;
            }
            closed = true;///首先在这里执行线程,首先设置boolean closed = true,防止close()在后面执行 函数的线程应继续执行后续的代码片段
        }
        ///如果NIO中的FileChanel对象与FileinputStream对象相关,则在NIO中关闭FileChanel对象
        if (channel != null) {
           channel.close();
        }
        // 释放文件描述了与Filedescriptor对象相关的所有资源
        fd.closeAll(new Closeable() {
            public void close() throws IOException {
               close0();////调用本地函数关闭文件
           }
        });
    }
    //获取文件描述符Filedescriptor对象
    public final FileDescriptor getFD() throws IOException {
        if (fd != null) {
            return fd;
        }
        throw new IOException();
    }
    ///将当前FileinputStream对象与NIO中的FileChanel联系起来
    public FileChannel getChannel() {
        synchronized (this) {
            if (channel == null) {
                channel = FileChannelImpl.open(fd, path, true, false, this);
            }
            return channel;
        }
    }

    private static native void initIDs();

    private native void close0() throws IOException;

    static {
        initIDs();
    }
    ////重写Objectt.classfinalize()函数,当对象被销毁时,JVM会自动调用此函数
    ///不建议通过finalize()函数调用close()函数关闭当前fileinputstream对象,建议在使用fileinputstream对象时手动调用close()函数
    protected void finalize() throws IOException {
        if ((fd != null) &&  (fd != null) &&  (fd != FileDescriptor.in)) {
            /* if fd is shared, the references in FileDescriptor
             * will ensure that finalizer is only called when
             * safe to do so. All references using the fd have
             * become unreachable. We can call close()
             */
            close();
        }
    }
}
1.1、FileInputStream.classskip()函数和available()函数

这个nioo可以通过skip()函数从这个-data.txt文件跳过n个字节进行后续操作,通过available()函数返回与这个fileinputstream对象相关的nio-data.txt文件还可以进行字节数量的后续操作,如下所示:

package com.xxx.bio;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
public class FileInputStreamTest {
   public static void main(String[] args) throws IOException {
      InputStream is = new FileInputStream("D:\\nio-data.txt");
      System.out.println(is.available());
      is.skip(5);
      System.out.println(is.available());
   }
}

程序运行结果如下: clipboard

1.2、模板方法模式

InputStream 定义为抽象基类 read()、skip()、available() 等抽象方法, FileInputStream、为了提供特定的功能,需要实现这些方法。例如:

// InputStream 抽象法
public abstract int read() throws IOException;

// FileInputStream 具体实现
public int read() throws IOException {
    return read0();  // 调用本地方法实现
}

字节流读取接口通过模板方法模式统一,子类只注重具体的读取逻辑,提高了代码的可扩展性。

1.3、适配器模式(Adapter Pattern)

  文件读取的基础操作依赖于操作系统(例如) Linux 的 read() 系统调用),FileInputStream 通过 native 该方法将这些系统调用到封装中 Java 接口(如 read()、close(),使上层代码不需要关心具体操作系统的差异。

private native int read0() throws IOException;  // 适应系统级读取操作
private native void close0() throws IOException;  // 适应系统级关闭操作

底层系统的复杂性通过适配器模式被屏蔽,跨平台的统一文件读取接口被提供。

1.4、代理模式(Proxy Pattern)

  FileDescriptor 是系统级文件句柄的代理对象,FileInputStream 通过 fd.attach(this) 将自己与描述符绑定。当流量关闭时,描述符会触发资源释放(如 close0())。这种设计允许多个流共享相同的描述符(如通过 getFD() 获取),但最终由最后一个关联流负责关闭。

fd.attach(this);  // 绑定流量和描述符
fd.closeAll(/* 关闭回调 */);  // 所有相关流关闭后释放资源

文件句柄的生命周期管理通过代理模式实现,避免资源泄漏。

二、Randomacesfile源码分析及使用方法详细分析

  RandomAccessFile 是 Java IO 系统中文件读取的基本类别用于在文件中的任何位置读写。Randomacesfile实现了Dataoutputput.interface和DataInput.interface有两个接口:读写java基本数据类型(byte,short,int,long,double,float,boolean,char) 与UTF-8字符串法有效地与IO流继承系统的其他部分分离。由于不支持装饰设计模式,不能与OutputStream和InputStream的子类结合使用。Randomacesfile之所以随机访问文件,是因为它将文件视为一个大型字节数组,然后通过游标(cursor)或者移动文件指针(可以理解为数组中索引读取或写入数组中任何位置的字节),从而实现文件的随机访问。相应的读写模式将在Randomacesfile结构方法中引入,共有4种。如下所示:

读写模式 解释 "r" 只读打开。调用结果对象的任何东西 write 所有的方法都会导致抛出 IOException。 "rw" 打开阅读和写入。 "rws" 打开阅读和写入。相对于 "rw","rws" 还需要将“文件内容”或“元数据”的每个更新同步写入基本存储设备。 "rwd" 打开以便读取和写入,相对于 "rw","rwd" 还需要将“文件内容”的每个更新同步写入基本存储设备。

当操作文件存储在本地基本存储设备上时(如硬盘, NandFlash等),rw" 、"rws" 、"rwd“只有两者有区别,区别如下: ①、当模式是 "rws" 并且 操作基本存储设备上的文件;然后,每次“更改文件内容(如执行write()函数)” 或 “修改文件元数据(如文件mtime)”时,这些变化将同步到基本存储设备; ②、当模式是 "rwd" 并且操作基本存储设备上的文件;然后,每次“更改文件内容(如执行write()函数)”时,都会将这些改变同步到基础存储设备上; ③、当模式是 "rw" 并且 操作是基本存储设备上的文件;然后,当文件关闭时,“文件内容修改”将同步到基本存储设备上。在“更改文件内容”时,是否会立即同步,取决于系统底层的实现。

  RandomAccessFile.class的源码如下

package java.io;
import java.nio.channels.FileChannel;
import sun.nio.ch.FileChannelImpl;
public class RandomAccessFile implements DataOutput, DataInput, Closeable {
    ///文件描述符
    private FileDescriptor fd;
    ///NIO中的FileChanel可以在getChanel()中更有效地操作文件 函数中将当与FileChanel相关的FileinputStream对象
    private FileChannel channel = null;
    private boolean rw;
    //在构造函数中,通过File对象获得的文件路径保存在该变量中
    private final String path;
    ///在close()函数中(关闭当前Randomacesfile 线程同步锁定对象的对象函数)
    private Object closeLock = new Object();
    private volatile boolean closed = false;///目前Randomacesfile 标记是否关闭
    
    //只读模式,没有写作权限,如果文件不存在,就不会创建文件。
    private static final int O_RDONLY = 1;
    //有读写权限的读写模式。如果没有文件,将创建文件。当模式下的数据发生变化时,它不会立即写入底层存储设备。
    private static final int O_RDWR =   2;
    //同步读写模式具有读写模式的所有特点。当文件内容或元数据发生变化时,它将立即同步写入底层存储设备。
    private static final int O_SYNC =   4;
    //同步读写模式具有读写模式的所有特点,当文件内容发生变化时,会立即同步写入底层存储设备。
    private static final int O_DSYNC =  8;

    public RandomAccessFile(String name, String mode)
        throws FileNotFoundException
    {
        this(name != null ? new File(name) : null, mode);
    }

    public RandomAccessFile(File file, String mode)
        throws FileNotFoundException
    {
        // 将String类型变量name定义为接收操作文件的路径名,如果文件为null,则name赋值为null。
        String name = (file != null ? file.getPath() : null);
        int imode = -1;
        if (mode.equals("r"))
            imode = O_RDONLY;//情况1:字符串model=rimode=1
        else if (mode.startsWith("rw")) {
            imode = O_RDWR;//情况2:以rw开头的字符串model(可以是rws或rwd,也可以是rw+任何字符串),imode=2
            rw = true;
            if (mode.length() > 2) {
                if (mode.equals("rws"))
                    imode 
|= O_SYNC;//情况3:字符串model=rwsimode=6
                else if (mode.equals("rwd"))
                    imode |= O_DSYNC;//情况4:字符串model=rwdimode=10
                else
                    imode = -1;///model不属于情况1、2、3、4的其余情况,imode=-1
            }
        }
        if (imode < 0)//model不属于情况1、2、3、在4的其他情况下,Illegalargumentexception
            throw new IllegalArgumentException("Illegal mode \"" + mode
                                               + "\" must be one of "
                                               + "\"r\", \"rw\", \"rws\","
                                               + " or \"rwd\"");
        根据rw状态监测文件的读写权限,获得java安全管理器。                                        
        SecurityManager security = System.getSecurityManager();
        if (security != null) {
            security.checkRead(name);
            if (rw) {
                security.checkWrite(name);
            }
        }
        if (name == null) {
            throw new NullPointerException();//文件的路径名==null,抛出Nullpointerexception
        }
        if (file.isInvalid()) {
            //当File对象的isInvalid()函数返回true时,抛出FilenotFoundexception
            throw new FileNotFoundException("Invalid file path");
        }
        fd = new FileDescriptor();
        fd.attach(this);// 绑定当前的Randomacesfile和文件描述符(用于资源回收)
        path = name;
        open(name, imode);// 最终调用本地函数(native修改)open0()打开文件
    }
    //获取文件描述符Filedescriptor对象
    public final FileDescriptor getFD() throws IOException {
        if (fd != null) {
            return fd;
        }
        throw new IOException();
    }
    ///将当前的Randomacesfile对象与NIO中的Filechanel相关联
    public final FileChannel getChannel() {
        synchronized (this) {
            if (channel == null) {
                channel = FileChannelImpl.open(fd, path, true, rw, this);
            }
            return channel;
        }
    }
     ////native修改的本地函数,目前,Randomacesfile对象以指定的读写模式打开指定文件,为后续的read()函数打开指定文件readBytes()函数、seek()准备函数
    private native void open0(String name, int mode)
        throws FileNotFoundException;
    
    private void open(String name, int mode)
        throws FileNotFoundException {
        open0(name, mode);
    }

    public int read() throws IOException {
        return read0();
    }
     ///native修改的本地函数,目前Randomacesfile对象每次从一个指定文件中读取一个字节;
    //如果没有读取文件的末尾,则返回读取字节的ASCII编码,如果已读取文件的末尾,则返回-1
    private native int read0() throws IOException;
    ///native修改的本地函数,目前Randomacesfile对象每次从指定文件读取len字节到byte b[]数组的[off,off+len)索引位置;
    ///如果没有读取文件的末尾,返回已读取的byte b[]数组中累计字节的数量(所有累计读取的字节都是通过ASCII编码的),如果已经读取了文件的末尾,则返回-1
    private native int readBytes(byte b[], int off, int len) throws IOException;

    public int read(byte b[], int off, int len) throws IOException {
        return readBytes(b, off, len);
    }

    public int read(byte b[]) throws IOException {
        return readBytes(b, 0, b.length);
    }

    public final void readFully(byte b[]) throws IOException {
        readFully(b, 0, b.length);
    }
    ///从打开的文件中读取len字节到指定的byte[]数组b,将len字节放入byte[]数组b[off,off+len)索引位置。
    public final void readFully(byte b[], int off, int len) throws IOException {
        int n = 0;///累计读取byte[]数组b中字节的数量
        do {
            //count=-1点,说读取到文件的末尾。
    public final void readFully(byte b[], int off, int len) throws IOException {
        int n = 0;//累计读取byte[]数组B中的字节数
        do {
            //count=-1点,说读取到文件的末尾。
            //count>0:00,说是从本次打开的文件中读取的(len - n)数组b从字节到byte[][off + n,off + len)索引位置。
            int count = this.read(b, off + n, len - n);
            if (count < 0)
                throw new EOFException();
            n += count;////累加读到的字节总数量
        } while (n < len);///当累计阅读字节总数时>=当len跳出循环时
    }
    ///目前,Randomacesfile对象可以从指定文件(大字节数组)跳过n个字节(n<后续操作(如通过read()函数读取)文件的字节总数
    public int skipBytes(int n) throws IOException {
        long pos;///当文件被视为大型字节数组时,pos表示当前操作该数组时索引位置
        long len;当文件被视为大字节数组时,len表示数组的长度
        long newpos;///当文件被视为一个大字节数组时,newpos表示要跳(重新指向)到达索引位置 

        if (n <= 0) {
            return 0;
        }
        pos = getFilePointer();///获取Randomacesfile对象正在操作的文件(大字节数组)的索引位置
        len = length();///获取文件(大字节数组)的长度
        newpos = pos + n;///计算跳跃(重新指向)到达的索引位置 
        if (newpos > len) {
            newpos = len;//如果索引越界,将索引置于文件(大字节数组)的最后一个索引位置
        }
        seek(newpos);通过native修改的函数,将文件(大字节数组)的索引置为newpos

        /* return the actual number of bytes skipped */
        return (int) (newpos - pos);///回到字节数量的实际跳跃
    }

    public void write(int b) throws IOException {
        write0(b);
    }
    ///native修改的本地函数,当前Randomacesfile对象在指定文件中写入一个字节
    private native void write0(int b) throws IOException;
    ///native修改的本地函数,当前Randomacesfile对象每次都写入bytete b[]数组中[off,off+len)索引位置的字节
    private native void writeBytes(byte b[], int off, int len) throws IOException;

    public void write(byte b[]) throws IOException {
        writeBytes(b, 0, b.length);
    }

    public void write(byte b[], int off, int len) throws IOException {
        writeBytes(b, off, len);
    }
    当文件被视为大型字节数组时,///native修改的本地函数将函数返回到当前操作(读写)到该数组的索引位置
    public native long getFilePointer() throws IOException;

    public void seek(long pos) throws IOException {
        if (pos < 0) {
            throw new IOException("Negative seek offset");
        } else {
            seek0(pos);
        }
    }
    当文件被视为大型字节数组时,///native修改的本地函数可以跳跃到该数组的指定索引位置
    private native void seek0(long pos) throws IOException;
    当文件被视为大型字节数组时,///native修改的本地函数可以获得该数组的长度
    public native long length() throws IOException;
    当文件被视为大型字节数组时,///native修改的本地函数可以设置该数组的长度
    public native void setLength(long newLength) throws IOException;

    public void close() throws IOException {
        synchronized (closeLock) {// 通过synchronized 防止多线程重复关闭
            if (closed) {
                return;
            }
            closed = true;///首先在这里执行线程,首先设置boolean closed = true,防止close()在后面执行 函数的线程应继续执行后续的代码片段
        }
        ///如果NIO中的FileChanel对象与FileinputStream对象相关,则在NIO中关闭FileChanel对象
        if (channel != null) {
            channel.close();
        }
        // 释放文件描述了与Filedescriptor对象相关的所有资源
        fd.closeAll(new Closeable() {
            public void close() throws IOException {
               close0();////调用本地函数关闭文件
           }
        });
    }
    ///阅读boolean类型的数据
    public final boolean readBoolean() throws IOException {
        int ch = this.read();///boolean类型占一个字节,调用native修改的read0()函数读取一个字节
        if (ch < 0)
            throw new EOFException();
        return (ch != 0);
    }
    ///阅读一个byte类型的数据
    public final byte readByte() throws IOException {
        int ch = this.read();//byte类型占1个字节,可以通过调用native修改的read0()函数读取1个字节
        if (ch < 0)
            throw new EOFException();
        return (byte)(ch);
    }
    ///读取一个不符号的byte类型数据
    public final int readUnsignedByte() throws IOException {
        int ch = this.read();///无符号byte类型占1个字节,调用native修改的read0()函数
        if (ch < 0)
            throw new EOFException();
        return ch;
    }
    //读取一个short类型的数据
    public final short readShort() throws IOException {
        int ch1 = this.read();//short类型占2个字节,占16位(bit),第一次调用native修改的read0()函数读取高8位(bit)表示一个字节
        int ch2 = this.read();///第二次调用native修改的read0()函数读取低8位(bit)表示一个字节
        if ((ch1 
| ch2) < 0)
            throw new EOFException();
        return (short)((ch1 << 8) + (ch2 << 0));//高8位(bit)和低8位(bit)相加,short类型数据组合成2字节(占16bit位)
    }
    ///读取一个不符号的short类型数据
    public final int readUnsignedShort() throws IOException {
        int ch1 = this.read();///无符号short类型占2个字节,占16位(bit),第一次调用native修改的read0()函数读取了高8位的函数(bit)表示一个字节
        int ch2 = this.read();///第二次调用native修改的read0()函数读取低8位(bit)表示一个字节
        if ((ch1 | ch2) < 0)
            throw new EOFException();
        return (ch1 << 8) + (ch2 << 0);//高8位(bit)和低8位(bit)相加,无符号short类型数据组合成2字节(占16bit位置)
    }
    ///读取char类型的数据
    public final char readChar() throws IOException {
        int ch1 = this.read();//char类型占2个字节,占16位(bit),第一次调用native修改的read0()函数读取高8位(bit)表示一个字节
        int ch2 = this.read();///第二次调用native修改的read0()函数读取低8位(bit)表示一个字节
        if ((ch1 | ch2) < 0)
            throw new EOFException();
        return (char)((ch1 << 8) + (ch2 << 0));//高8位(bit)和低8位(bit)相加,char类型数据组合成2字节(占16bit位)
    }
    ///读取int类型的数据
    public final int readInt() throws IOException {
        int ch1 = this.read();///int类型占4个字节,占32位(bit),第一次调用native修改的read0()函数读取第一个8位(bit)表示第一个字节
        int ch2 = this.read();read0()函数第二次调用native修改,读取第28位(bit)表示第二个字节
        int ch3 = this.read();read0()函数第三次调用native修改,读取第三个8位(bit)表示第三个字节
        int ch4 = this.read();read0()函数读取第四个8位,第四次调用native修改(bit)表示第四个字节
        if ((ch1 
| ch2 | ch3 | ch4) < 0)
            throw new EOFException();
        return ((ch1 << 24) + (ch2 << 16) + (ch3 << 8) + (ch4 << 0));//4个字节相加,组合成4个字节(占32bit位)的int类型数据。
    }
    ///读取long类型数据,long类型占8个字节,占64位(bit)
    public final long readLong() throws IOException {
        //先读4个字节,高32位(bit),再读4个字节,低32个字节(bit),高32位(bit)和低32位(bit)相加,long类型数据组合成8字节(占64bit位)
        return ((long)(readInt()) << 32) + (readInt() & 0xFFFFFFFFL);
    }
    ///读取float类型的数据
    public final float readFloat() throws IOException {
        return Float.intBitsToFloat(readInt());
    }
    ///阅读double类型的数据
    public final double readDouble() throws IOException {
        return Double.longBitsToDouble(readLong());
    }
    ///一次读取一行数据,并返回读取的数据。
    public final String readLine() throws IOException {
        //创建一个用于接收读取数据的Stringbuffer对象。
    public final String readLine() throws IOException {
        ///创建StringBuffer对象,用于接收读取数据。
        StringBuffer input = new StringBuffer();
        ///声明int变量c用于接收读取数据,声明boolean变量eol,是否读取换行符。
        int c = -1;
        boolean eol = false;
        //通过循环不断读取数据。
        while (!eol) {
            switch (c = read()) {
            case -1://返回-1表示文件已读完。
            case '\n':
                eol = true;///返回n表示读到换行符,此时将eol放入true,跳出循环。
                break;
            case '\r':
                eol = true;///返回r因为不同的平台换行符不同,所以把eol放在true上看看是否有‘\n(windows操作系统的转换为“\r\n如果没有,将操作文件(大字节数组)的指针(索引)重置为‘\r下一个位置,然后跳出循环。
                long cur = getFilePointer();
                if ((read()) != '\n') {
                    seek(cur);
                }
                break;
            default:
                input.append((char)c);///每次操作到StringBuferfer 读取的字节添加到input中。
                break;
            }
        }
        //如果没有读取任何数据,请返回null。
        if ((c == -1) && (input.length() == 0)) {
            return null;
        }
        //执行到此时,表示读取了当前行数据,最终将input转换为String类型,然后返回。
        return input.toString();
    }

    public final String readUTF() throws IOException {
        return DataInputStream.readUTF(this);
    }
    ///将一个boolean类型数据写入到Randomacesfile对象正在操作的文件中
    public final void writeBoolean(boolean v) throws IOException {
        write(v ? 1 : 0);
        //written++;
    }
    ///在Randomacesfile对象正在操作的文件中写入一个byte类型的数据
    public final void writeByte(int v) throws IOException {
        write(v);
        //written++;
    }
    ///将一个short类型数据写入到Randomacesfile对象正在操作的文件中
    //因为Java 大端字节序默认使用(Big-Endian)存储是最有效的字节(MSB)前面,最低有效字节(LSB)在后。
    public final void writeShort(int v) throws IOException {
        write((v >>> 8) & 0xFF);///先将short类型(占2个字节,共16位)写入文件中(bit)
        write((v >>> 0) & 0xFF);//再次将short类型写入文件中(占2个字节,共16位)低8位(bit)
        //written += 2;
    }
   ///将一个char类型数据写入到Randomacesfile对象正在操作的文件中
    //因为Java 大端字节序默认使用(Big-Endian)存储是最有效的字节(MSB)首先,最低有效字节(LSB)在后。
    public final void writeChar(int v) throws IOException {
        Char类型(占2个字节,共16位)高8位(bit)
        write((v >>> 8) & 0xFF);
        char类型(占2个字节,共16位)低8位(bit)
        write((v >>> 0) & 0xFF);
        //written += 2;
    }
   //将一个int类型数据写入RandomAccessFile对象正在操作的文件中
    //因为Java 大端字节序默认使用(Big-Endian)存储是最有效的字节(MSB)前面,最低有效字节(LSB)在后。
    public final void writeInt(int v) throws IOException {
        ///第一个8位bit(从左到右)写入int类型(占4个字节,共32位)
        write((v >>> 24) & 0xFF);
        //将int类型写入文件中(占4个字节,共32位)第2位8位bit(从左到右)
        write((v >>> 16) & 0xFF);
        ///将int类型(占4个字节,共32位)的第三个8位bit(从左到右)写入文件中
        write((v >>>  8) & 0xFF);
        //最后将int类型写入文件中(占4个字节,共32位)第4位8位bit(从左到右)
        write((v >>>  0) & 0xFF);
        //written += 4;
    }
    ///将一个long类型的数据写入到Randomacesfile对象正在操作的文件中
    //因为Java 大端字节序默认使用(Big-Endian)存储是最有效的字节(MSB)前面,最低有效字节(LSB)在后。
    public final void writeLong(long v) throws IOException {
        //先将long类型写入文件中(占8个字节,共64位)第一个8位bit(从左到右)
        write((int)(v >>> 56) & 0xFF);
        ///在文件中写入long类型的第二个8位bit(从左到右)
        write((int)(v >>> 48) & 0xFF);
        ///将long类型的第三个8位bit(从左到右)写入文件中
        write((int)(v >>> 40) & 0xFF);
        ///在文件中写入long类型的第四个8位bit(从左到右)
        write((int)(v >>> 32) & 0xFF);
        ///在文件中写入long类型的第五个8位bit(从左到右)
        write((int)(v >>> 24) & 0xFF);
        ///在文件中写入long类型的第6个8位bit(从左到右)
        write((int)(v >>> 16) & 0xFF);
        ///在文件中写入long类型的第7个8位bit(从左到右)
        write((int)(v >>>  8) & 0xFF);
        ///最后将long类型的第8位bit(从左到右)写入文件中
        write((int)(v >>>  0) & 0xFF);
        //written += 8;
    }
    ///将float类型数据写入到Randomacesfile对象正在操作的文件中
    public final void writeFloat(float v) throws IOException {
        writeInt(Float.floatToIntBits(v));
    }
    ///将一个double类型数据写入到Randomacesfile对象正在操作的文件中
    public final void writeDouble(double v) throws IOException {
        writeLong(Double.doubleToLongBits(v));
    }
    ///将一个字符串写入到Randomacesfile对象正在操作的文件中
    public final void writeChars(String s) throws IOException {
        int clen = s.length();////获得字符串的长度
        int blen = 2*clen;//因为Java中的一个字符占两个字节,因此,字节数组的长度是字符串长度的两倍
        byte[] b = new byte[blen];
        char[] c = new char[clen];
        s.getChars(0, clen, c, 0);//首先将字符串写入字符数组中
        //因为Java 大端字节序默认使用(Big-Endian)存储是最有效的字节(MSB)前面,最低有效字节(LSB)在后。
        for (int i = 0, j = 0; i < clen; i++) {
            //所以首先将每个字符(char类型)的高8位bit写入字节数组,将每个字符(char类型)的低8位bit写入字节数组
            b[j++] = (byte)(c[i] >>> 8);
            b[j++] = (byte)(c[i] >>> 0);
        }
        writeBytes(b, 0, blen);///通过writebytes()函数将转换后的字节数组写入文件
    }

    public final void writeUTF(String str) throws IOException {
        DataOutputStream.writeUTF(str, this);
    }

    private static native void initIDs();

    private native void close0() throws IOException;

    static {
        initIDs();
    }
}
2.1、大端字节序(Big-Endian)Randomacesfile存储 写入问题(以writeint()函数为例)

  writeInt(int v) 函数将一个 int 类型整数(共) 4 按顺序写入文件。因为底层 write() 函数每次只能写入 1 所以需要字节 int 的 4 逐一提取并写入个字节。源代码如下:

   ///将一个int类型的数据写入到Randomacesfile对象操作的文件中
    //因为Java 大端字节序默认使用(Big-Endian)存储是最有效的字节(MSB)前面,最低有效字节(LSB)在后。
    public final void writeInt(int v) throws IOException {
        //首先将int类型的第一个8位bit(从左到右)写入文件中(占4个字节,共32位)
        write((v >>> 24) & 0xFF);
        //将int类型写入文件中(占4个字节,共32位)第2位8位bit(从左到右)
        write((v >>> 16) & 0xFF);
        ///将int类型(占4个字节,共32位)的第三个8位bit(从左到右)写入文件中
        write((v >>>  8) & 0xFF);
        //最后将int类型写入文件中(占4个字节,共32位)第4位8位bit(从左到右)
        write((v >>>  0) & 0xFF);
        //written += 4;
    }

①、例如,用二进制写入int类型的数据1、666、688、888,表示0110 0011 0101 0111 1010 0111 0111 1000,需要从左到右写入第一个字节0110 0011时,会执行

write((v >>> 24) & 0xFF);

整个过程,如下所示:

step1:先右移24位
0110 0011 0101 0111 1010 0111 0111 1000 >>> 24
结果为(>>> 是无符号右移,高位补充 0.避免符号扩展干扰):
0000 0000 0000 0000 0000 0000 0110 0011
step2:剩下的8位和0xFF(1111,1111)&运算
0000 0000 0000 0000 0000 0000 0110 0011
&                             1111 1111
结果为:
0110 0011

最终将0110 将Randomacesfile对象正在操作的文件中写入0011(占1个字节)。 ②、然后从左到右写入第二个字节0101 0111时,会执行

write((v >>> 16) & 0xFF);

整个过程如下所示:

step1:先右移16位
0110 0011 0101 0111 1010 0111 0111 1000 >>> 16
结果为(>>> 是无符号右移,高位补充 0.避免符号扩展干扰):
0000 0000 0000 0000 0110 0011 0101 0111
step2:剩下的16位和0xFF(111,111)&运算
0000 0000 0000 0000 0110 0011 0101 0111
&                             1111 1111
结果为:
0101 0111

最终将0101 0111(占1个字节)写入Randomacesfile对象正在操作的文件中。 ③、然后从左到右写入第三个字节1010 0111时,会执行

write((v >>>  8) & 0xFF);

整个过程如下所示:

step1:先右移8位
0110 0011 0101 0111 1010 0111 0111 1000 >>> 8
结果为:
0000 0000 0110 0011 0101 0111 1010 0111
step2:将剩余的24位与0xFF(111,111)进行&运算
0000 0000 0110 0011 0101 0111 1010 0111
&                             1111 1111
结果为:
1010 0111

最终将1010 0111(占1个字节)写入Randomacesfile对象正在操作的文件中。 ④、最后,从左到右写入第四个字节0111 1000时,会执行

write((v >>>  0) & 0xFF);

整个过程如下所示:

step1:先右移0位,其实原值是不变的,直接用来参与运算
0110 0011 0101 0111 1010 0111 0111 1000 >>> 0
结果为(>>> 是无符号右移,高位补充 0.避免符号扩展干扰):
0110 0011 0101 0111 1010 0111 0111 1000
step2:与0xFF(1111、1111)一起进行原值&运算
0110 0011 0101 0111 1010 0111 0111 1000
&                             1111 1111
结果为:
0111 1000

最终将0111 Randomacesfile对象正在操作的文件中写入1000(占1个字节)。   WriteByte()函数等其他函数writeShort()函数、writeChar()函数...与writeint()函数的原理相同,但最终字节的数量可能不同,但从左到右依次写入高字节。

2.2、大端字节序(Big-Endian)RandomAccesfile存储 以readInt()函数为例)中的阅读问题

  readInt() 函数会将1个 int 类型整数(共) 4 从Randomacesfile) 读取操作文件 来吧。因为底层 read() 函数每次只能读取 1 所以需要字节 int 的 4 首先逐个读取个字节,然后调用read()4次 在拼接之前,读取函数的结果移动。源代码如下所示:

    ///读取int类型的数据
    public final int readInt() throws IOException {
        int ch1 = this.read();///int类型占4个字节,占32位(bit),第一次调用native修改的read0()函数读取第一个8位(bit)表示第一个字节
        int ch2 = this.read();read0()函数第二次调用native修改,读取第28位(bit)表示第二个字节
        int ch3 = this.read();//第三次调用native修改的read0()函数读取第三个8位的函数。(bit)表示第三个字节
        int ch4 = this.read();read0()函数读取第四个8位,第四次调用native修改(bit)表示第四个字节
        if ((ch1 | ch2 | ch3 | ch4) < 0)
            throw new EOFException();
        return ((ch1 << 24) + (ch2 << 16) + (ch3 << 8) + (ch4 << 0));//4字节加,int类型数据组合成4字节(占32bit位)
    }

最后一步

(ch1 << 24) + (ch2 << 16) + (ch3 << 8) + (ch4 << 0)

4次调用read() 按照大端字节序读取函数的结果(Big-Endian)整个拼接过程如下(与writeint()函数的执行原理相反): ①、例如,读取的一种int类型的数据是1、666、688、888,用二进制表示0110 0011 0101 0111 1010 0111 0111 1000,读取这个数字到内存后,ch1、ch2、ch3、ch4分别为:

ch1:0110 0011
ch2:0101 0111
ch3:1010 0111
ch4:0111 1000

拼接前的最后一步移项过程如下:

ch1 << 24:0110 0011 0000 0000 0000 0000 0000 0000
ch2 << 16:0000 0000 0101 0111 0000 0000 0000 0000 
ch3 << 8: 0000 0000 0000 0000 1010 0111 0000 0000
ch4 << 0: 0000 0000 0000 0000 0000 0000 0111 1000

拼接工艺如下:

 0110 0011 0000 0000 0000 0000 0000 0000
+0000 0000 0101 0111 0000 0000 0000 0000 
+0000 0000 0000 0000 1010 0111 0000 0000
+0000 0000 0000 0000 0000 0000 0111 1000
结果为:
 0110 0011 0101 0111 1010 0111 0111 1000
2.3、Randomacesfile使用示例

  在使用Randomacesfile时,可以使用多线程读写一个文件,以提高整个文件的读写效率,如下所示:

package com.xxx.bio;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
public class RandomAccessFileIOTest {
   public static void main(String[] args) {
      final File source = new File("F:\/realMe手机文件备份\/照片视频\/VID20260217183653.mp4");
      final File target = new File("D:\\copy.mp4");
      int threadNum = (int) Math
            .ceil(Math.ceil((double) source.length() / 1024 / 1024 / 20));
      ///只用线程池打开5个核心线程进行复制,ArrayBlockingQueue<>(10)队列长度为10
      ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(5, 100, 0, TimeUnit.SECONDS, new ArrayBlockingQueue<>(10), new ThreadFactory() {
         private final AtomicInteger threadCount = new AtomicInteger(1);
         private final String namePrefix = "MyPool-thread-";

         @Override
         public Thread newThread(Runnable r) {
            Thread t = new Thread(r, namePrefix + threadCount.getAndIncrement());
            t.setDaemon(false);
            t.setPriority(Thread.NORM_PRIORITY);
            return t;
         }
      });

      for (int i = 0; i < threadNum; i++) {
         threadPoolExecutor.execute(new MyRunnable(i, source, target));
      }
      threadPoolExecutor.shutdown();
   }
}

class MyRunnable implements Runnable {
   private int num;
   private File source;
   private File target;

   MyRunnable(int num, File source, File target) {
      this.num = num;
      this.source = source;
      this.target = target;
   }

   @Override
   public void run() {
      try (RandomAccessFile sourceFile = new RandomAccessFile(source, "rw");
          RandomAccessFile targetFile = new RandomAccessFile(target, "rw");) {
         System.out.println(Thread.currentThread().getName() + “线程启动”);
         sourceFile.seek(num * 1024 * 1024 * 20);
         targetFile.seek(num * 1024 * 1024 * 20);
         byte[] buffer = null;
         if ((sourceFile.length() - sourceFile.getFilePointer()) < 1024 * 1024 * 20) {
            buffer = new byte[(int) (sourceFile.length() - sourceFile
                  .getFilePointer())];
         } else {
            buffer = new byte[1024 * 1024 * 20];
         }
         sourceFile.read(buffer);
         targetFile.write(buffer);
      } catch (FileNotFoundException e) {
         e.printStackTrace();
      } catch (IOException e) {
         e.printStackTrace();
      }
      System.out.println(Thread.currentThread().getName() + “线程复制结束”;
   }
}

我的windows操作系统Findows:\realme手机文件备份\照片视频\路径下的VID20260217363.MP4文件通过多线程将上述代码复制到D盘根目录(D:copy下copy.在mp4文件中,执行结果如下: clipboard image

扩展JDK原生RandomAccessFile-增加缓冲区

  从Randomacesfile的源代码可以看出,Randomacesfile在读写操作中直接与底层介质传输数据。即使读写字节数据,也必须进行I/O操作,大大降低了其工作效率。我们可以通过内置数据缓存区来提高读写效率,Randomacesfile也可以这样操作。我们可以完全重构自己的带缓存的bufferedrandomacesfile。 类,如下所示:

package com.xxx.bio;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.util.Arrays;

public class BufferedRandomAccessFile extends RandomAccessFile {
   private static final int Default_Buffer_Size = 1024 * 8;
   private static final int MAX_BUFFER_SIZE = Integer.MAX_VALUE - 8;
   private static final long BuffMask_ = ~(((long) Default_Buffer_Size) - 1L);

   //表示缓存区是否有未flush数据。
   private boolean hasDatas;
   //表示是否同步操作,将缓存内容flush。
   private boolean hasDatas;
   //表示是否同步操作,将缓存内容flush。
   private boolean syncNeeded_;
   //当前操作文件的索引位置(包括在缓存区)。
   private long cPos = 0L;
   //磁盘上操作文件的索引位置(存储介质)。
   private long diskPos_ = 0L;
   private long lo_, hi_ = 0L;
   private long maxHi_ = (long)Default_Buffer_Size;
   //是否到达文件的末尾。
   private boolean isEOF;
   //内置数组缓存区,默认尺寸为8k。
   private byte[] buffer;

   public BufferedRandomAccessFile(File file, String mode) throws IOException {
      this(file, mode, Default_Buffer_Size);
   }

   public BufferedRandomAccessFile(String name, String mode)
         throws IOException {
      this(name, mode, Default_Buffer_Size);
   }

   public BufferedRandomAccessFile(File file, String mode, int size)
         throws IOException {
      super(file, mode);
      init(size);
   }

   public BufferedRandomAccessFile(String name, String mode, int size)
         throws FileNotFoundException {
      super(name, mode);
      init(size);
   }

   ///初始化内置缓存区
   private void init(int size) {
      if (size < Default_Buffer_Size) {
         size = Default_Buffer_Size;
      } else if (size > MAX_BUFFER_SIZE) {
         size = MAX_BUFFER_SIZE;
      }
      buffer = new byte[size];
   }

   ///将缓存区的数据同步写入存储介质。
   public void sync() throws IOException {
      if (syncNeeded_) {
         ////在内置缓存区写入数据
         flush();
         ///强制将未在文件通道中写入磁盘的数据写入磁盘,并表示是否将文件元信息写入磁盘。
         getChannel().force(true);
         syncNeeded_ = false;
      }
   }

   // 在close之前,先刷新缓存区,防止缓存区中未写入的数据,然后将缓存区放入null,调用父类close释放资源。
   public void close() throws IOException {
      this.flush();
      this.buffer = null;
      super.close();
   }

   ////将缓存区内容写入存储介质中
   public void flush() throws IOException {
      this.flushBuffer();
   }

   ////将缓存内容写入存储介质
   private void flushBuffer() throws IOException {
      if (hasDatas) {
         if (diskPos_ != lo_)
            super.seek(lo_);
         int len = (int) (cPos - lo_);
         super.write(buffer, 0, len);
         diskPos_ = cPos;
         hasDatas = false;
      }
   }

   //填充缓存区的数据。返回实际填充多少字节的数据。
   private int fillBuffer() throws IOException {
      int nextChar = 0;
      int nChars = buffer.length;
      //通过一个循环,将数据填充到缓存区域,直到缓存区域被填充或文件读取到最后。
      while (nChars > 0) {
         int n = super.read(buffer, nextChar, nChars);
         if (n < 0)
            break;
         nextChar += n;
         nChars -= n;
      }
      if ((nextChar < 0) && (isEOF = (nextChar < buffer.length))) {
         //将是缓存区未填充部分的全用-1初始化。
         Arrays.fill(buffer, nextChar, buffer.length, (byte) 0xff);
      }
      diskPos_ += nextChar;
      return nextChar;
   }

   ////跳过指定字节数
   public void seek(long pos) throws IOException {
      if (pos >= hi_ 
|| pos < lo_) {
         flushBuffer();
         lo_ = pos & BuffMask_;
         maxHi_ = lo_ + (long) buffer.length;
         if (diskPos_ != lo_) {
            super.seek(lo_);
            diskPos_ = lo_;
         }
         int n = fillBuffer();
         hi_ = lo_ + (long) n;
      } else {
         if (pos < cPos) {
            flushBuffer();
         }
      }
      cPos = pos;
   }

   public long getFilePointer() {
      return cPos;
   }

   public long length() throws IOException {
      return Math.max(cPos, super.length());
   }

   public int read() throws IOException {
      if (cPos >= hi_) {
         if (isEOF)
            return -1;

         seek(cPos);
         if (cPos == hi_)
            return -1;
      }
      byte res = buffer[(int) (cPos - lo_)];
      cPos++;
      return ((int) res) & 0xFF;
   }

   public int read(byte[] b) throws IOException {
      return read(b, 0, b.length);
   }

   public int read(byte[] b, int off, int len) throws IOException {
      if (cPos >= hi_) {
         if (isEOF)
            return -1;

         seek(cPos);
         if (cPos == hi_)
            return -1;
      }
      len = Math.min(len, (int) (hi_ - cPos));
      int buffOff = (int) (cPos - lo_);
      System.arraycopy(buffer, buffOff, b, off, len);
      cPos += len;
      return len;
   }

   public void write(int b) throws IOException {
      if (cPos >= hi_) {
         if (isEOF && hi_ < maxHi_) {
            hi_++;
         } else {
            seek(cPos);
            if (cPos == hi_) {
               hi_++;
            }
         }
      }
      buffer[(int) (cPos - lo_)] = (byte) b;
      cPos++;
      hasDatas = true;
      syncNeeded_ = true;
   }

   public void write(byte[] b) throws IOException {
      write(b, 0, b.length);
   }

   public void write(byte[] b, int off, int len) throws IOException {
      while (len > 0) {
         int n = writeAtMost(b, off, len);
         off += n;
         len -= n;
         hasDatas = true;
         syncNeeded_ = true;
      }
   }

   private int writeAtMost(byte[] b, int off, int len) throws IOException {
      if (cPos >= hi_) {
         if (isEOF && hi_ < maxHi_) {
            hi_ = maxHi_;
         } else {
            seek(cPos);
            if (cPos == hi_) {
               hi_ = maxHi_;
            }
         }
      }
      len = Math.min(len, (int) (hi_ - cPos));
      int buffOff = (int) (cPos - lo_);
      System.arraycopy(b, off, buffer, buffOff, len);
      cPos += len;
      return len;
   }
}
3.1、Bufferedrandomcesfile 性能对比
package com.xxx.bio;

import java.io.*;

public class BufferedRandomAccessFilefTest {
   public static void main(String[] args) {
      long startTime;
      long endTime;
      File source = new File("F:\realMe手机文件备份\\/照片视频\VID20217183620217.mp4");
      File target = new File("D:\\copy.mp4");
      byte[] buffer = new byte[1024];
      startTime = System.currentTimeMillis();
      int len;
      try (RandomAccessFile sourceFile = new RandomAccessFile(source, "rw");
          RandomAccessFile targetFile = new RandomAccessFile(target, "rw")) {
         while ((len = sourceFile.read(buffer)) != -1) {
            targetFile.write(buffer, 0, len);
         }
         endTime = System.currentTimeMillis();
         System.out.println(“Randomacesfile复制耗时” + (endTime - startTime)
               + "ms");
      } catch (Exception e) {
      }

      startTime = System.currentTimeMillis();
      try (BufferedInputStream bis = new BufferedInputStream(
            new FileInputStream(source));
          BufferedOutputStream bos = new BufferedOutputStream(
                new FileOutputStream(target));) {
         while ((len = bis.read(buffer)) != -1) {
            bos.write(buffer, 0, len);
         }
         endTime = System.currentTimeMillis();
         System.out.println("BufferedInputStream/Buffedoutstream复制耗时”
               + (endTime - startTime) + "ms");
      } catch (Exception e) {
      }

      startTime = System.currentTimeMillis();
      try (BufferedRandomAccessFile sourceFile = new BufferedRandomAccessFile(
            source, "rw");
          BufferedRandomAccessFile targetFile = new BufferedRandomAccessFile(
                target, "rw")) {
         while ((len = sourceFile.read(buffer)) != -1) {
            targetFile.write(buffer, 0, len);
         }
         endTime = System.currentTimeMillis();
         System.out.println(“Bufferedrandrandomacesfile复制耗时” + (endTime - startTime)
               + "ms");
      } catch (Exception e) {
      }
   }
}