简体   繁体   English

HashMap到txt文件-在Java OOP中编写键和值

[英]HashMap to txt file - writing key & value in Java OOP

I'm creating a ChatBox program that responds to keywords being typed into my Java program. 我正在创建一个ChatBox程序,该程序响应在Java程序中键入的关键字。 I have a list of responses stored as a HashMap, in an external txt file. 我在外部txt文件中将响应列表存储为HashMap。 I want to create a method that enables me to add to a HashMap new keysword(key):responses(values) and therefore, add to the external txt file. 我想创建一个方法,使我可以向HashMap中添加新的keyword(key):responses(values),因此可以将其添加到外部txt文件中。

I already have key: values inserted into this text file, but I'm having difficult trying to add new keys: values to it, in the correct format, and then retrieving them. 我已经有key:值插入到此文本文件中,但是我很难尝试以正确的格式向其添加新的key:值,然后检索它们。

I have a method called 'addtoresponses()' which should take the string parameters from the method and insert them into a hashMap. 我有一个名为“ addtoresponses()”的方法,该方法应从该方法中获取字符串参数,并将其插入到hashMap中。 The hashMap will then be written to a txt file using another method, from another class called 'listMap'. 然后,将使用另一个方法从另一个名为“ listMap”的类将hashMap写入txt文件。

When I run my code, the hashMap does write to the external text file, so that seems to work (it writes it to the external text file, so it can be used by another method later on). 当我运行代码时,hashMap确实会写入外部文本文件,因此似乎可以正常工作(它将其写入外部文本文件,因此以后可以由另一种方法使用)。 However, when I run my program again, I instantly get an error message stating that; 但是,当我再次运行程序时,我立即收到一条错误消息,指出:

Missing response for Hello in file missing-map.txt (hello being the key inserted). 文件missing-map.txt中Hello缺少响应(hello是插入的密钥)。

It appears that the key:value I'm adding in, is the losing the 'value' part of whatever I'm typing into my method. 看来,我要添加的key:value是丢失我在方法中键入的内容的“ value”部分。 I've been told that it's possibly my format ie it should be stored in the following way; 有人告诉我,这可能是我的格式,即应该以以下方式存储:

    **key
    response all on one line of length
    key
    another response all on one line
    etc.**

But I'm unclear in how I can achieve this. 但是我不清楚如何实现这一目标。 I'm pretty sure it's not the method that's inserting the HashMap into the txt file. 我很确定这不是将HashMap插入txt文件的方法。 I believe it's how I'm putting the values into the HashMap but I'm not greatly confident. 我相信这是我将值放入HashMap的方式,但我不太自信。

Would greatly appreciate it if someone could look over my code and try and see where I'm going wrong, in relation to why this error message is appearing and how I can fix it. 如果有人可以查看我的代码并尝试查看我在哪里出了问题,以及为什么会出现此错误消息以及如何修复它,将不胜感激。

I've posted the code in below; 我将代码发布在下面;

Constructor for InstructorMode >> InstructorMode的构造方法>>

public InstructorMode()
{
    helper = new FileAssistance();
    edits = new HashMap<String, String>();
}

Method for adding to HashMap (in InstructorMode class) >> 添加到HashMap的方法(在InstructorMode类中)>>

public void addtoresponse(String key, String value)
{
    edits.put(key, value); 
    helper.listaMap(edits, "missing-map.txt");
}

Method for adding to external txt file (class called FileAssistance) >> 添加到外部txt文件的方法(称为FileAssistance的类)>>

    public void listaMap(HashMap<String, String> map, String filename)
     {
    if(map != null) {
        try (FileWriter writer = new FileWriter(filename, true)) {
            for(String key : map.keySet()) {
                String value = map.get(key);
                if(value == null) {
                    System.out.println("Warning: " +
                                       key + " in listaMap.");
                    value = "Not sure";
                }
                writer.write(key.trim());
                writer.write('\n');
                writer.write(value.trim());
                writer.write('\n');
            }                    
            writer.close();
        }
        catch(IOException e) {
            System.out.println("Issue: " + filename +
                               " in listaMap");
        }
    }
    else {
        System.out.println("Null map passed to listaMap.");
    }
}

Would appreciate any help on this! 希望对此有所帮助!

Edit - code which reads a HashMap >> 编辑-读取HashMap的代码>>

  public HashMap<String, String> lookatM(String filename)
    {
    HashMap<String, String> map = new HashMap<>();
    try (BufferedReader reader =
            new BufferedReader(new FileReader(filename))) {
        String word;
        word = reader.readLine();
        while(word != null) {
            String response = reader.readLine();
            if(response != null) {
                response = response.trim();
                if(response.length() != 0) {
                    map.put(word, response);
                }
                else {
                    System.out.println("Blank response for " +
                                       word + " in file " +
                                       filename);
                }
            }
            else {
                System.out.println("Missing response for " +
                                   word + " in file " +
                                   filename);
            }
            word = reader.readLine();
        }
    }
    catch(IOException e) {
        System.out.println("Problem reading file: " + filename +
                           " in LookatM");
    }
    return map;
}

You can use a java.lang.Properties which is basically an HashMap that can interact with a .properties file. 您可以使用java.lang.Properties ,它基本上是一个可以与.properties文件进行交互的HashMap

A properties file, in turn, is nothing more than a list of key and values separated by '=' 反过来,属性文件不过是键和值列表(用“ =”分隔)

For example, you can have a property file with the following content: 例如,您可以拥有一个包含以下内容的属性文件:

Name=Sauron    
Attitude=Nice in a peculiar way
[...]

You can load a property file in a Properties object using Properties.load() 您可以使用Properties.load()将属性文件加载到Properties对象中

If you want to add more key/value pairs just use the method Properties.setProperty() 如果要添加更多键/值对,请使用Properties.setProperty()方法

If you want to save the state of your Properties object to the backing properties file, just use Properties.store 如果要将“属性”对象的状态保存到支持属性文件,只需使用Properties.store

For more information, see the Properties javadoc 有关更多信息,请参见Properties javadoc

Additionally, here you can find a tutorial on how to use the Properties in your code 此外,您可以在此处找到有关如何在代码中使用属性的教程。

You are doing reader.readLine twice in loop and thats the reason of your output message. 您正在循环执行两次reader.readLine ,这就是输出消息的原因。 You just should use 'standard' 您只应该使用“标准”

while((word = reader.readLine()) != null){
 //loop body
}

I haven't tried running your code on my machine but here are few suggestions just by looking at your snippets - 我没有尝试在我的机器上运行您的代码,但是仅通过查看代码片段,这里有一些建议-
1. Please check for any hidden characters in your file containing key-value rows. 1.请检查文件中是否包含键值行的任何隐藏字符。 One more thing to check if you have empty newline at the end of a file. 检查文件末尾是否有空换行符的另一件事。
2. One more thing to check if you are getting this error for just last key-value pair in your file. 2.再检查一下文件中的最后一个键值对是否出现此错误。
3. I know this is obvious but debug in IDE can be helpful too!! 3.我知道这很明显,但是在IDE中进行调试也很有帮助!

One last thing, if you have to store map into file and reconstruct from file then you can serialize map object into file and reconstruct object from that serialized file. 最后一件事,如果您必须将地图存储到文件中并从文件中重建,则可以将地图对象序列化为文件并从该序列化文件中重建对象。 Here is simple tutorial tutorial I found online. 下面是简单的教程教程我在网上找到。 properties file also do that job as mentioned above. 属性文件也可以执行上述操作。

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

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