当前所在位置:珠峰网资料 >> 计算机 >> 计算机等级考试 >> 正文
2015年计算机二级考试JAVA知识点整理(22)
发布时间:2010/12/12 18:24:52 来源:城市学习网 编辑:ziteng
  1.1.3.2.5 随机访问
  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);
  }
  }
  }
  这个程序简单的读取字节序列然后输出它们。
  如果有访问位置,这个技术是很有用的,文件中的附近字节几乎在同时被读取。例如,如果你在一个排序的文件上实现二分法查找,这个方法可能很有用。如果你在一个巨大的文件上的任意点做随机访问的话就没有太大价值。
广告合作:400-664-0084 全国热线:400-664-0084
Copyright 2010 - 2017 www.my8848.com 珠峰网 粤ICP备15066211号
珠峰网 版权所有 All Rights Reserved