我在内存中有一个文件,我想构造一个 HashMap 类型:
HashMap<Date, List<String>>
脱离它。该文件的示例记录如下:
[1987-11-19=[Ashwin Anthony, 100000065750184, /sdcard/DirPrime/1389422388122.jpg]
我的示例代码是:
public void readSDMap(){
try{
File toRead=new File("/sdcard/DirPrime/filetwo.txt");
FileInputStream fis=new FileInputStream(toRead);
Scanner sc=new Scanner(fis);
HashMap<Date,List<String>> mapInFile=new HashMap<Date,List<String>>();
String currentLine;
while(sc.hasNextLine()){
currentLine=sc.nextLine();
StringTokenizer st=new StringTokenizer(currentLine,"=",false);
**//error here**
The method put(Date, List<String>) in the type
HashMap<Date,List<String>> is not applicable for the
arguments (String, String)
mapInFile.put(st.nextToken(),st.nextToken());
}
fis.close();
System.out.println(mapInFile);
//print All data in MAP
for(Map.Entry<Date,List<String>> m :mapInFile.entrySet()){
// System.out.println(m.getKey()+" : "+m.getValue());
}
}catch(Exception e){}
}
如何重建 map ,我无法理解将值作为 map 的一部分的逻辑。这是一个列表。
编辑 (这只是一个快速的解决方案,请忽略我将字符串转换为日期的肮脏方式) 解析日期后:
Date d = null;
try {
d = new SimpleDateFormat("yyyy-MM-dd"/*, current*/).parse(st.nextToken());
} catch (ParseException e) {
e.printStackTrace();
}
Date d1 = new java.sql.Date(d.getTime());
mapInFile.put(d1,st.nextToken());
我有兴趣解决等式的后半部分,即构建列表。
最佳答案
map 键是一个日期,你必须修复这一行:
Date date = new SimpleDateFormat("yyyy-MM-dd", Locale.ENGLISH).parse(st.nextToken());
mapInFile.put(date, Arrays.asList(st.nextToken().split(" ,")));
请注意,拆分右侧字符串时可以使用多个定界符。
关于java - 文件到 HashMap,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21059945/