Java 2: File / RandomAccessFile

File

java.io.File类用于表示文件(目录);
File类只用于表示文件(目录)的信息(名称,大小等),不能用于文件内容的访问;
File 内容的访问,需要借助Steam;

RandomAccessFile

RandomAccessFile Java 提供的对文件内容访问的类,可以读写文件;
RandomAccessFile 支持随机访问文件,可以访问文件的任意位置;
其中有个指针,指向被访问的位置,默认打开文件时,指针在开头 pointer=0 ;

Java世界里的文件模型
在硬盘上的文件是 byte byte byte 存储的 ,是数据的集合;
RandomAccessFile访问文件的模式
读写模式 : “rw”
只读模式 : “r”

写操作
raf.write(int): 只写一个字节(后8位);同时指针指向下一个位置,准备再次写入;

 /**
     * Writes the specified byte to this file. The write starts at
     * the current file pointer.
     *
     * @param      b   the {@code byte} to be written.
     * @exception  IOException  if an I/O error occurs.
     */
    public void write(int b) throws IOException {
        // Android-changed: Implement on top of low-level API, not directly natively.
        // write0(b);
        scratch[0] = (byte) (b & 0xff);
        write(scratch, 0, 1);
    }

读操作
int b = raf.read() :读一个字节;

/**
     * Reads a byte of data from this file. The byte is returned as an
     * integer in the range 0 to 255 ({@code 0x00-0x0ff}). This
     * method blocks if no input is yet available.
     * <p>
     * Although {@code RandomAccessFile} is not a subclass of
     * {@code InputStream}, this method behaves in exactly the same
     * way as the {@link InputStream#read()} method of
     * {@code InputStream}.
     *
     * @return     the next byte of data, or {@code -1} if the end of the
     *             file has been reached.
     * @exception  IOException  if an I/O error occurs. Not thrown if
     *                          end-of-file has been reached.
     */
    public int read() throws IOException {
        // Android-changed: Implement on top of low-level API, not directly natively.
        // return read0();
        return (read(scratch, 0, 1) != -1) ? scratch[0] & 0xff : -1;
    }

seek()
及时文件是空的,也可以调到某个pointer位置,执行读写操作;这就是RandomAccess;

RandomAccessFile rw = new RandomAccessFile(file, "rw");
        long length = rw.length();
        System.out.println(length);
        rw.seek(33);
        rw.write('x');
        rw.seek((32));
        rw.write('y');

        rw.seek(32);
        byte[] bytes1 = new byte[2];
        rw.read(bytes1);
        java.lang.String s = new java.lang.String(bytes1);
        System.out.println(s);
        rw.close();
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 1.java.io.RandomAccessFile:该类设计用来专门读写文件数据。其基于指针进行读写,即:总是在...
    新手程序员阅读 626评论 0 2
  • 一.java.io.File类 java.io.File类用于表示文件/目录 File只用于表示文件的信息(名称,...
    liangxifeng833阅读 783评论 0 1
  • 1、Java编码基础 对于Java文件中,是采用的双字节编码utf-16be; 其中,中文占用2个字节,英文占用2...
    方研梅阅读 927评论 0 1
  • 1.1.1 Java异常处理机制 异常结构中的父类Throwable类,其下子类Exceptionlei类和Err...
    海若Hero阅读 314评论 0 1
  • 摧毁数组 金克斯的迫击炮! 实现一个摧毁(destroyer)函数,第一个参数是待摧毁的数组,其余的参数是待摧毁的...
    有事找叮当阅读 238评论 0 0