当前所在位置:珠峰网资料 >> 计算机 >> 计算机等级考试 >> 正文
2015年计算机二级考试JAVA知识点整理(24)
发布时间:2010/12/12 18:25:52 来源:城市学习网 编辑:ziteng
  1.1.3.2.7 高速缓存
  关于硬件的高速缓存的详细讨论超出了本文的讨论范围。但是在有些情况下软件高速缓存能被用于加速I/O。考虑从一个文本文件里面以随机顺序读取一行的情况,这样做的一个方法是读取所有的行,然后把它们存入一个ArrayList (一个类似Vector的集合类):
  import java.io.*;
  import java.util.ArrayList;
  public class LineCache {
  private ArrayList list = new ArrayList();
  public LineCache(String fn) throws IOException {
  FileReader fr = new FileReader(fn);
  BufferedReader br = new BufferedReader(fr);
  String ln;
  while ((ln = br.readLine()) != null)
  list.add(ln);
  br.close();
  }
  public String getLine(int n) {
  if (n < 0)
  throw new IllegalArgumentException();
  return (n < list.size() ? (String) list.get(n) : null);
  }
  public static void main(String args[]) {
  if (args.length != 1) {
  System.err.println("missing filename");
  System.exit(1);
  }
  try {
  LineCache lc = new LineCache(args[0]);
  int i = 0;
  String ln;
  while ((ln = lc.getLine(i++)) != null)
  System.out.println(ln);
  } catch (IOException e) {
  System.err.println(e);
  }
  }
  }
  getLine 方法被用来获取任意行。这个技术是很有用的,但是很明显对一个大文件使用了太多的内存,因此有局限性。一个代替的方法是简单的记住被请求的行最近的100行,其它的请求直接从磁盘读取。这个安排在局域性的访问时很有用,但是在真正的随机访问时没有太大作用。
广告合作:400-664-0084 全国热线:400-664-0084
Copyright 2010 - 2017 www.my8848.com 珠峰网 粤ICP备15066211号
珠峰网 版权所有 All Rights Reserved