I have a text file which has data as follows:
Surrender~abc~nov@2012
Surrender~bnc~bhdgvx
Surrender~nkhjb~bcdjh
.
.
.
I want to separate the data row by row and store second and third column values in Hashmap as 2nd -> key and 3rd -> value and check if the value entered by user exist in the Hashmap and return true.
I tried following but getting java.lang.ArrayIndexOutOfBoundsException: 3..Please guide.
HashMap hm = new HashMap();
FileInputStream fstream = new FileInputStream("Surrender.txt");
DataInputStream in = new DataInputStream(fstream);
BufferedReader br = new BufferedReader(new InputStreamReader(in));
String strLine;
while ((strLine = br.readLine()) != null) {
String[] parts = strLine.split("~");
for (int i = 0; i <= parts.length; i++) {
if(!parts[i].equalsIgnoreCase("Surrender")){
String key=parts[i];
String value=parts[i++];
if(key!=null && value!=null)
hm.put(key,value);
}
}
}
System.out.println("HashMap size..." + hm.size());
in.close();
Since each of your lines looks like this:
there are three parts after splitting by
~:Surrenderabcnov@2012These parts are numberd from
0to2.Solution: Don’t loop over the
parts. Do this instead:Drop these lines:
Note: Use a generic
Map: