从文本文件读取到哈希映射或列表 [英] Read from a Text File into a hash map or list

查看:143
本文介绍了从文本文件读取到哈希映射或列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


可能重复:

使用deimeter选项卡在Java中解析字符串“ \t”使用拆分

如何从文本文件中读取字符串并存储在HashMap的?文件包含两列。

How do I read strings from a text file and store in a hashmap? File contains two columns.

文件类似于:

标题en_CA

1根据您的保单的法定条件,我们必须告知您保单的保险范围将在收到此信件后15天的上午12:01停止生效。已解决。

1 In accordance with the Statutory Conditions of your policy, we must advise that coverage under your policy will cease to be in effect 12:01 a.m., 15 days following receipt of this letter at the post office to which it is addressed.

列(如标题和en_CA或1和按照...)由制表符分隔而不是空格。

The columns (like Title and en_CA or 1 and In accordance...) are separated by a tab not a space.

谢谢

推荐答案

这应该可以帮到你。你需要做一些检查,以确保每一行实际上有两个部分,并可能将代码包装在一些try / catch块中。我假设您希望第一列成为键,第二列成为值。

This should get you started. You'll want to do some checking along the way to make sure each line actually has two parts and probably wrap the code in some try/catch blocks. I'm assuming you want the first column to be the key and the second column to be the value.

public class ReadToHashmap {
    public static void main(String[] args) throws Exception {
        Map<String, String> map = new HashMap<String, String>();
        BufferedReader in = new BufferedReader(new FileReader("example.tab"));
        String line = "";
        while ((line = in.readLine()) != null) {
            String parts[] = line.split("\t");
            map.put(parts[0], parts[1]);
        }
        in.close();
        System.out.println(map.toString());
    }
}

输入:

title   en_CA
1       In accordance blah bla blah

输出:

{1=In accordance blah bla blah, title=en_CA}

这篇关于从文本文件读取到哈希映射或列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆