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.
     * 

* 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();

你可能感兴趣的:(Java 2: File / RandomAccessFile)