随机访问

RandomAccessFile 是一个进行随机文件I/O(在字节层次上)的类。这个类提供一个seek方法,和 C/C++中的相似,移动文件指针到任意的位置,然后从那个位置字节可以被读取或写入。

seek方法访问底层的运行时系统因此往往是消耗巨大的。一个更好的代替是在RandomAccessFile上建立你自己的缓冲,并实现一个直接的字节read方法。read方法的参数是字节偏移量(>= 0)。这样的一个例子是:

 import java.io.*;

 

public class ReadRandom {

   private static final int DEFAULT_BUFSIZE = 4096;

 

   private RandomAccessFile raf;

 

   private byte inbuf[];

 

   private long startpos = -1;

 

   private long endpos = -1;

 

   private int bufsize;

 

   public ReadRandom(String name) throws FileNotFoundException {

        this(name, DEFAULT_BUFSIZE);

   }

 

   public ReadRandom(String name, int b) throws FileNotFoundException {

        raf = new RandomAccessFile(name, "r");

        bufsize = b;

        inbuf = new byte[bufsize];

   }

 

   public int read(long pos) {

        if (pos < startpos || pos > endpos) {

            long blockstart = (pos / bufsize) * bufsize;

            int n;

            try {

                 raf.seek(blockstart);

                 n = raf.read(inbuf);

            } catch (IOException e) {

                 return -1;

            }

            startpos = blockstart;

            endpos = blockstart + n - 1;

            if (pos < startpos || pos > endpos)

                 return -1;

        }

        return inbuf[(int) (pos - startpos)] & 0xffff;

   }

 

   public void close() throws IOException {

        raf.close();

   }

 

   public static void main(String args[]) {

        if (args.length != 1) {

            System.err.println("missing filename");

            System.exit(1);

        }

        try {

            ReadRandom rr = new ReadRandom(args[0]);

            long pos = 0;

            int c;

            byte buf[] = new byte[1];

            while ((c = rr.read(pos)) != -1) {

                 pos++;

                 buf[0] = (byte) c;

                 System.out.write(buf, 0, 1);

            }

            rr.close();

        } catch (IOException e) {

            System.err.println(e);

        }

   }

}

这个程序简单的读取字节序列然后输出它们。

如果有访问位置,这个技术是很有用的,文件中的附近字节几乎在同时被读取。例如,如果你在一个排序的文件上实现二分法查找,这个方法可能很有用。如果你在一个巨大的文件上的任意点做随机访问的话就没有太大价值。

 

posted @ 2018-08-06 23:37  borter  阅读(524)  评论(0编辑  收藏  举报