0

到目前为止,我一直在逐行读取带有 BufferedReader 的文件,但是,现在我希望能够只存储该行上的第二个单词。我将我的行存储在哈希图中以便于查找。

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

谁能帮助我只阅读每行的第二个单词?

谢谢!

4

1 回答 1

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);
    }
于 2012-10-10T00:09:43.453 回答