简体   繁体   中英

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

i have a txt file with this form :

 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 :

     <"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(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:

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.

But why are you not using an OOP way? 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", ...

Edit: Explaining OOP way

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. 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}]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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