【问题标题】:Print data from a text file imported into a hash map, ignore characters从导入哈希映射的文本文件中打印数据,忽略字符
【发布时间】:2019-11-05 21:11:46
【问题描述】:

我有一个包含以下内容的文本文件:

example.txt

#ignore
#ignore line
#ignore line again
1234567
8940116
12131415

我想将 example.txt 文件读入 eclipse 并将数据添加到 hashmap 中。我希望列表按数字顺序排列,并且我希望它忽略文本文件中的任何 cmets(任何带有 # 的文本)。我想按如下方式打印哈希图:

输出:

1234567
8940116
12131415

【问题讨论】:

  • 你的句子都是以“我想要...”开头的,但并不明显你已经尝试了任何东西来实现你想要的。您可以在这里找到,也可以在其他地方在线找到如何读取文件、如何跳过某些行、如何检查字符串是否以某个字符开头......首先自己尝试一下。如果您无法进一步显示您卡在哪里。除此之外,地图是充当键和值的数据对的容器。您的示例数据看起来不像它们代表这样的对。

标签: java eclipse import hashmap


【解决方案1】:

您不需要哈希图来仅存储字符串。映射用于键值对。如果要将文件中的每一行放入集合中,请使用 Lists。 ArrayLists、LinkedList 维护插入顺序。你可以使用它们中的任何一个。如果你想要排序列表,你可以使用 TreeList。

    BufferedReader reader;
    List<String> list = new ArrayList<String>();
    try {
        reader = new BufferedReader(new FileReader(
                "example"));
        String line = reader.readLine();
        while (line != null) {
            if(!line.startsWith("#"){
                list.add(line);
              }
              line = reader.readLine();
        }
        reader.close();
    } catch (IOException e) {
        e.printStackTrace();
    }

【讨论】:

  • 我更喜欢哈希图。输出格式为 [, , ,]。我添加了打印语句
【解决方案2】:

Map 的目的是存储对 Key/Value,对于单个集合,您可以使用List,它的效率要高得多,打印部分是您的工作,无论集合类型是什么

List<String> values = new ArrayList<>();
try (BufferedReader reader = new BufferedReader(new FileReader("filename"))) {
    String line;
    while ((line = reader.readLine()) != null) {
        if (!line.startsWith("#")) {
            values.add(line);
        }
    }
} catch (IOException e) {
    e.printStackTrace();
}

for (String v : values)
    System.out.println(v);

【讨论】:

    猜你喜欢
    • 2013-11-23
    • 2012-02-11
    • 1970-01-01
    • 2018-09-19
    • 1970-01-01
    • 2021-04-03
    • 2015-08-18
    • 2021-11-19
    • 1970-01-01
    相关资源
    最近更新 更多