• 随机访问


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

            }

       }

    }

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

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

     

  • 相关阅读:
    判断奇偶数2
    判断奇偶数
    15.09.29
    .
    Java代码
    Handler 接收Parcelable ArrayList时返回空的错误
    Android Binder设计与实现
    xml解析代码示例
    解析rss和atom文件出现乱码问题
    使用Html.fromHtml将html格式字符串应用到textview上面
  • 原文地址:https://www.cnblogs.com/borter/p/9434261.html
Copyright © 2020-2023  润新知