高速缓存

关于硬件的高速缓存的详细讨论超出了本文的讨论范围。但是在有些情况下软件高速缓存能被用于加速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行,其它的请求直接从磁盘读取。这个安排在局域性的访问时很有用,但是在真正的随机访问时没有太大作用。

 

原文地址:https://www.cnblogs.com/borter/p/9434271.html