简体   繁体   English

将txt文件读取到哈希图中,并用“ \\ t”分隔

[英]read txt file to hashmap, split by “\t”

i have a txt file with this form : 我有这种形式的txt文件:

 1     01/01/2018 01:00 1915    8,4
 1     01/01/2018 02:00 2111    8,8

After reading the file i want to store it into a Map with this structure : 读取文件后,我想将其存储到具有以下结构的Map中:

     <"Key1",1> <"Key2",01/01/2018 01:00>  <"Key3",1915>  <"Key4",8,4>

this is the import code 这是导入代码

        BufferedReader buf = new BufferedReader(new 
 FileReader("test.txt"));
        ArrayList<String> words = new ArrayList<>();
        String lineJustFetched = null;
        String[] wordsArray;
        Map<String,String> map = new HashMap<>();

        while(true){
            lineJustFetched = buf.readLine();
            if(lineJustFetched == null) {
                break;
            } else {
                wordsArray = lineJustFetched.split("\t");
                for(String each : wordsArray){
                        words.add(each);
                  //  System.out.println(words.toString());
                    map.put("Key1",each);
                    System.out.println(map.toString());

                }
            }
        }
        buf.close();

the problem that i don't know what to put into the map to have this structure 我不知道要放入地图中具有这种结构的问题

   <"Key1",1> <"Key2",01/01/2018 01:00>...

use for with an index for索引

for(int i = 0 ; i < wordsArray.length ; i++) {
    map.put("Key"+(i+1), wordsArray[i]);
}

EDIT 编辑

following the comment, you could set up an array with field names and use it 在评论之后,您可以设置一个具有字段名称的数组并使用它

String[] fieldNames = {"id", "date", "whatever"};
for(int i = 0 ; i < wordsArray.length ; i++) {
    map.put(fieldNames[i], wordsArray[i]);
}

Place the results of split into the map like this, assigning the keys: 像这样将split的结果放置到地图中,并分配键:

wordsArray = lineJustFetched.split("\t");
map.put("Key1", wordsArray[0]);
map.put("Key2", wordsArray[1]);
map.put("Key3", wordsArray[2]);
map.put("Key4", wordsArray[3]);

Well, first of all your error is that you've hard coded Key1 as the key for your Hashmap, you should change that. 好吧,首先,您的错误是您已将Key1硬编码为Hashmap的密钥,您应该更改它。

But why are you not using an OOP way? 但是,为什么不使用OOP方法呢? Create an object of the data in the line you are reading and add that to a list or something, this way you can also have meaningfull names for your "Keys" instead of simply "Key1", "Key2", ... 在要读取的行中创建数据对象,然后将其添加到列表或其他内容中,这样,您还可以为“键”使用有意义的名称,而不仅仅是“ Key1”,“ Key2”,...

Edit: Explaining OOP way 编辑:解释OOP方式

First of all, I'm not really familiar with java typenames / built-in functions, so you might need to change some parts of this code, but the concept remains the same. 首先,我对Java类型名/内置函数不是很熟悉,因此您可能需要更改此代码的某些部分,但是概念保持不变。 If you have any questions just ask me :) 如果您有任何问题,请问我:)

// the object that you can store your data in
class YourObject
{
    int _someKey;
    DateTime _dateTime; // I'm not sure which is the correct Java typename here, but I'm sure you'll understand what I mean
    int _someValue;
    double _otherValue;

    // getters and setters as you need..
}

// container for all your data to be fetched from the file
ArrayList<YourObject> data = new ArrayList<YourObject>()

// in your fetching loop:
wordsArray = lineJustFetched.split("\t");
YourObject yourObject = new YourObject();
yourObject.setSomeKey(int.Parse(wordsArray[0]));
yourObject.setDateTime(DateTime.Parse(wordsArray[1]));
yourObject.setSomeValue(int.Parse(wordsArray[2]));
yourObject.setOtherValue(double.Parse(wordsArray[3]));
data.add(yourObject);

Hope this will serve your purpose. 希望这能达到您的目的。 I have updated your code as per your requirement. 我已根据您的要求更新了您的代码。 Input will be same as you have mentioned in the question. 输入将与您在问题中提到的相同。

BufferedReader buf = new BufferedReader(new FileReader("src/com/test/test.txt"));
ArrayList<Map> allWordsList = new ArrayList<>();
String lineJustFetched = null;
String[] wordsArray;
Map<String, String> map;
String[] fieldNames = { "Id", "Date", "Code", "No" };

while ((lineJustFetched = buf.readLine()) != null) {
    wordsArray = lineJustFetched.split("\\s+");
    map = new HashMap<>();
    for (int i = 0, j = i; i < wordsArray.length; i++) {
        if (i == 1) map.put(fieldNames[j++], wordsArray[i] + " " + wordsArray[i + 1]);
        if (i != 1 && i != 2) map.put(fieldNames[j++], wordsArray[i]);
    }
    allWordsList.add(map);
}
buf.close();

System.out.println(allWordsList);

You will get the output as 您将获得输出为

[{No=8,4, Id=1, Code=1915, Date=01/01/2018 01:00}, 
{No=8,8, Id=1, Code=2111, Date=01/01/2018 02:00}]

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

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