简体   繁体   English

FileHashMap <K, V> :重复使用相同的哈希图

[英]FileHashMap<K, V>: Reuse the same hashmap

   FileHashMap<int, String> myMap = new FileHashMap<int, String>("/myFile");       
   myMap.put(1, "First");
   myMap.put(2, "Second");
   myMap.save();
   myMap.close();

According to my understanding this code will save the Hashmap files on to disk... But when I am creating the object of FileHashMap again, like this: 根据我的理解,此代码会将Hashmap文件保存到磁盘上。但是当我再次创建FileHashMap的对象时,如下所示:

    FileHashMap<int, String> myMap = new FileHashMap<int, String>("/myFile");       
    if(myMap.containsKey(1){
    System.out.println("Yes");
    }
    else{
    System.out.println("No");
    }

This is giving the output as "No".. I want to reuse the file, reuse the Hashmap... How can I do this.. Can anybody explain?? 这给出的输出为“否”。我想重用文件,重用Hashmap ...我该怎么做。有人可以解释吗?

Here's your problem: the API is confusing. 这是您的问题: API令人困惑。 It says that "[a] FileHashMap is persistent by default," but the zero- and one-arg constructors (the one you're using which specifies the file name is the one-arg) create a new transient FileHashMap — that is, the file is deleted after the FileHashMap is closed. 它说“ [a] FileHashMap默认情况下是持久性的”,但是零和一个参数构造器(您使用的用于指定文件名的一个参数是一个参数)将创建一个新的瞬态 FileHashMap ,即, FileHashMap关闭后,该文件将被删除。 The two-arg constructor takes the filename and an int options flag, but there's no specific option for "persistent", so you just have to make sure the flag is not "transient" (to be precise, flags & FileHashMap.TRANSIENT == 0 ). 具有两个参数的构造函数采用文件名和一个int options标志,但是没有针对“ persistent”的特定选项,因此您只需确保该标志不是“ transient”(准确地说, flags & FileHashMap.TRANSIENT == 0 )。

In order to get it to save and open the file, pass 0 as the flag to the constructor (unless you want other options — read the docs) as such: 为了使其保存并打开文件,请将标记0传递给构造函数(除非您需要其他选项,请阅读文档),如下所示:

new FileHashMap<Integer, String>(fileName, 0);

Note that the generic parameter needs to be Integer rather than int , as comments have stated. 请注意,如注释所述,泛型参数需要为Integer而不是int Also note that you probably want your file path to be something other than "/myFile" as that will most likely give you a permission denied error, unless you're running as root, which you probably shouldn't be. 还要注意,您可能希望文件路径不是“ / myFile”,因为这很可能会给您一个权限被拒绝的错误,除非您以root身份运行,否则可能不应该这样。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM