1

我的这个类 TagVertex 包含一种从文本文件中读取标签 value=string 的方法

并返回

    public class TagVertex extends Vertex<String> {

    @Override
    public String computeVertexValue() {
    String s = null;
    try {
        BufferedReader bf = new BufferedReader(new FileReader(MyDataSource.TagList1K));

      for(int i = 1; i < Integer.parseInt(this.getVertexId().substring(this.getVertexId().indexOf("g")+1)); i++){
          bf.readLine();
      }
      s= bf.readLine();
      bf.close();
    } catch (Exception e) {
        e.printStackTrace();
    }
            this.setVertexValue(s);

    return  s;
        }

该方法被调用 1000 次 ==> 文件也被读取 1000 次

最好使用数据库而不是文本文件?

4

2 回答 2

2

访问硬盘驱动器始终是一个非常缓慢的操作。数据库通常也访问硬盘驱动器,因此它们不一定更快。它们甚至可能更慢,因为当数据库不在同一个系统上运行时,会增加网络延迟(即使它在 localhost 上运行,由于进程间通信,您也会有延迟)。

我建议您读取一次文件并缓存该值。当您需要立即知道文件何时更改时,您可以使用新的 WatchService API 在文件更改时重新加载文件。这是一个教程。当立即注册文件系统级别的更改并不那么重要时,您还可以节省从硬盘驱动器读取顶点信息的时间,并且仅在超过几秒钟时重新读取该值。

于 2013-04-24T15:20:23.497 回答
2

您可以像这样创建自己的内存数据库。

private static final List<String> lines = new ArrayList<>();

@Override
public String computeVertexValue() {
    if (lines.isEmpty())
        try {
            BufferedReader br = new BufferedReader(new FileReader(MyDataSource.TagList1K));
            for (String line; (line = br.readLine()) != null; )
                lines.add(line);
            br.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    return lines.get(Integer.parseInt(this.getVertexId().substring(this.getVertexId().indexOf("g") + 1)));
}
于 2013-04-24T16:03:15.263 回答