简体   繁体   English

使用定界符\\ t分割文本文件并存储在Java中的哈希图中

[英]Split a text file using delimiter \t and store in hashmap in java

I have a text file of n columns and n rows separated by tab space.. How do i use split function to store the columns and rows into a hashmap.Please help. 我有一个n列和n行用制表符分隔的文本文件。如何使用拆分功能将列和行存储到哈希图中。请帮助。
My text file will be like.. 我的文本文件会像..

Dept Id Name Contact 部门ID名称联系人
IT 1 zzz 678 第1章678

ECE 2 ttt 789 欧洲经委会2 ttt 789

IT 3 rrr 908 IT 3 rrr 908

I tried the following.But it dint work. 我尝试了以下方法,但是效果不错。

Map<String,String> map=new HashMap<String,String>();
while(lineReader!=null)
{
String[] tokens = lineReader.split("\\t");
key = tokens[0];
values = tokens[1];
map.put(key , values );
System.out.println("ID:"+map.get(key ));
System.out.println("Other Column Values:"+map.get(values ));
}

This returns the key of the last entry(row) of the file and value as null. 这将返回文件的最后一个条目(行)的键,其值作为null。 But i need to store all rows and columns in the map. 但是我需要在地图上存储所有行和列。 How do i do it? 我该怎么做?

If I understand your data correctly, 如果我正确理解您的数据,

After

String[] tokens = lineReader.split("\\t");

is processed on the first line, you'd have 4 tokens in the array. 在第一行进行处理,则数组中将有4个令牌。

I think you are using wrong logic, if you want to store the map in the following way: 如果您想通过以下方式存储地图,我认为您使用的是错误的逻辑:

IT -> (1 ZZZ 678) .... etc then you need to process the data differently. IT->(1 ZZZ 678)....等,然后您需要对数据进行不同的处理。

What you are storing in the map is follows: IT -> 1 ECE -> 2 ... and so on. 您在地图中存储的内容如下:IT-> 1 ECE-> 2 ...,依此类推。

That's why you get null when you are trying to do: 这就是为什么您尝试执行以下操作时会得到null的原因:

map.get(value);

What you should instead print is the Key and map.get(key) . 您应该打印的是Keymap.get(key)

Actually, in any case I don't think Map is what you want (but I don't know what you really want). 实际上,无论如何我都不认为Map是您想要的(但是我不知道您真正想要的是什么)。

For now though, for your understanding of this problem try printing: 现在,为了您对这个问题的理解,请尝试打印:

System.out.println("Total collumns: "+ tokens.length);

Updated: 更新:

This should work for you. 这应该为您工作。 It isn't the most elegant implementation for what you want, but gets the job done. 它不是您想要的最优雅的实现,但是可以完成工作。 You should try improving it from here on. 您应该从现在开始尝试对其进行改进。

Map<String,String> map=new HashMap<String,String>();
while(lineReader!=null)
{
String[] tokens = lineReader.split("\\t");
key = tokens[1];
values = tokens[2]+tokens[3];
map.put(key , values );
System.out.println("ID:"+key);
System.out.println("Other Column Values:"+map.get(key));
}

Good luck! 祝好运!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM