简体   繁体   中英

How to create a HashMap from a text document and show specific keys and value

I am trying to create a simple method that will read a text file with a few lines of text separated by commas and split the text after the first comma into a key then every other comma until a new line into the value for that key.

Steps:

  1. Read File from ourFilePath
  2. Split the first word in each line ( DataEntry1 ) into a Key then everything after the first comma into the Value for that Key.
  3. After Search the Keys for the Key I am looking for and print out the Value of that key.

Example:

filetest.txt:

DataEntry1, Important, Stuff, Data, Clouds
DataEntry2, Boring, Stuff, Numbers, Cats
DataEntry3, Strange, Stuff, MoreData, Dogs

Code:

public static void getOurData(String ourFilePath, String ourDataName) throws Exception {
    Map<String, String> ourMap = new HashMap<String, String>();
    BufferedReader in = new BufferedReader(new FileReader(ourFilePath));
    String line = "";

    while ((line = in.readLine()) != null) {
        String parts[] = line.split(",", 2);

        ourMap.put(parts[1], parts[0]);
        System.out.println(ourMap.toString());
    }

    in.close();

So far I only have the reading from a file working, I am trying to figure out how to make each of the DataEntry into a Key for the HashMap ourMap and everything after into a Value for it as well.

After that I am positive I can finish Step 3 to search the Map for a specific key and print out that value.

it's seems ok, you need only to change the order of the argument when you call

ourMap.put(key, value);

try

while ((line = in.readLine()) != null) {
    String parts[] = line.split(",", 2);

    ourMap.put(parts[0], parts[1]); // change here
    System.out.println(ourMap.toString());
}

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