【问题标题】:How to only read second word on each line Java如何只读取每行 Java 中的第二个单词
【发布时间】:2012-10-10 00:02:20
【问题描述】:

到目前为止,我一直在使用 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) {
    }

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

谢谢!

【问题讨论】:

  • 使用split?
  • 我建议使用List 而不是HashMap
  • 我稍后会使用 HashMap 来进一步查找和操作数据。对我来说,这似乎是最好的结构,直到现在它都很好。使用 List 有什么好处?

标签: java file bufferedreader


【解决方案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);
    }

【讨论】:

  • 这对我帮助很大。但它仍然占据了第三个字。是否有办法告诉缓冲区阅读器转到下一行?
  • 谢谢!所以,如果我决定读第三个单词,我改变 j == 2?我还在搞 Java...
  • 如果我想要我的 的 HashMap 怎么办,因为 tokenizer.nextToken() 是一个字符串,我一直在尝试转换它。但没有成功。
  • 使用Integer.valueOf(String s)方法。
猜你喜欢
  • 2011-04-14
  • 2013-05-20
  • 2019-07-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-11-19
  • 1970-01-01
  • 2013-10-07
相关资源
最近更新 更多