简体   繁体   中英

How to only read second word on each line Java

until now I have been reading in a file with BufferedReader line by line, however, now I would like to be able to only store the second word on that line. I have my line stored in a hashmap for easy lookup.

     int i=0;

     HashMap<Integer, String> mapHash = new HashMap<Integer, String>();

    try {
        BufferedReader in = new BufferedReader(new FileReader("file"));
        String st;


        while ((st = in.readLine()) != null) {
            st = st.trim();
            //store the lexicon with position in the hashmap
            mapHash.put(i, st);
            i++;

        }
        in.close();
    } catch (IOException e) {
    }

Could anyone help me out to only read the second word on each line?

Thanks!

For example

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.StringTokenizer;

//...
try (BufferedReader in = new BufferedReader(new FileReader("file"));) {
        Map<Integer, String> mapHash = new HashMap<>();
        int i = 0;
        String st;

        while ((st = in.readLine()) != null) {
            st = st.trim();
            StringTokenizer tokenizer = new StringTokenizer(st);
            int j = 0;
            while (tokenizer.hasMoreTokens()) {
                if (j == 1) {
                    mapHash.put(i, tokenizer.nextToken());
                    break;
                } else {
                    tokenizer.nextToken();
                    j++;
                }
            }
            //store the lexicon with position in the hashmap
            i++;
        }
    } catch (IOException e) {
        throw new RuntimeException(e);
    }

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