从文本文档插入到 Hashmap

Inserting from Text document to Hashmap

你好我正在尝试制作一个小程序来从文本文档中获取信息并将该信息插入哈希图中。我不明白的棘手部分是如何区分信息,以便它进入我希望它进入哈希图中的字段。

现在你可以说我将要使用的文本文档已经有各种 "labels"。例如,文本文档中显示的信息格式如下:35=22, 20=0, 52=20180608-19:51:02.352, 56=ALPH

我正在考虑将所有这些信息插入到一个 Hashmap 类型中。我只是想区分信息,例如:

BufferedReader reader = 
 new BufferedReader(newFileReader("C:\Users\darroyo\Documents\pruebasx.txt"));

String line=reader.readLine();
Map<Integer,String> hm1 = new HashMap<Integer,String>();
                    hm1.put(1, arg1)
                    hm1.put(2, arg1)
                    hm1.put(3, arg1)

此处 1 将读取标签 35 并放入值 22,哈希映射值 2 将读取标签 56 并放入值 ALPH。这样的信息怎么识别呢?另外,如果我有多行格式相似的行,会发生什么情况,它们是否也会被传递到哈希图上,还是我必须创建一个新的?

您可以尝试使用 Properties class.

Properties pro = new Properties();
FileReader fr = new FileReader("C:\Users\darroyo\Documents\pruebasx.properties"); 
pro.load(fr);                    
Map<Integer,String> map = new HashMap<Integer,String>();
map.put(1,pro.getProperty(35));
map.put(2,prp.getProperty(56));

我不确定您的文件是否可以包含 rows/line 中断。如果不是,只需将 while 语句替换为 line = reader.readLine();.

Map<Integer,String> hm1 = new HashMap<Integer,String>();
String line;
// while there is a line to be read
while ((line = reader.readLine()) != null) {
    // we need to tokenize the line. the common separator is ", "
    // so that it what we shall split it by, to get an array of each value between ", "
    String[] tokens = line.split(",\s"); //(in regex, \s matches a whitespace such as a space)
    // if the space is unreliable, it can be made optional: line.split(",\s?")
    // loop for each record
    for (int i = 0; i != tokens.length; i++) {
        // next we need to get the "data" portion of the record, which is after the '='
        /*
        ** we could use regex again
        ** i.e. tokens[i].split("=")[1] will be the "data"
        ** but as a general rule, if you can do it easily without regex, don't use regex.
        ** it might look innocent enough, but a lot goes on in a regex engine!
        **
        ** instead we just get the index of '=' in the string
        ** add 1 to move past it
        ** and then get the characters from that index onward
        ** i.e. tokens[i].substring(tokens[i].indexOf('=')+1)
        */
        //get the index at which the data starts in the string
        int dataIndex = tokens[i].indexOf('=') + 1;
        //get the chars from that index onward
        String data = tokens[i].substring(dataIndex);
        //insert it into the map
        hm1.put(new Integer(i),data);
    }
}