如何只读取每行Java上的第二个单词

时间:2012-10-10 00:02:20

标签: java file bufferedreader

直到现在我一直在读一个带BufferedReader的文件,但是,现在我希望只能在该行上存储第二个单词。我将我的行存储在hashmap中以便于查找。

     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) {
    }

有人可以帮我解读每一行的第二个字吗?

谢谢!

1 个答案:

答案 0 :(得分:1)

例如

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);
    }