如何让我的哈希图正确打印到文件



我正在做一个项目,我有一个文件,程序可以访问该文件以获取有关不同年份不同犯罪的信息。然后,它需要根据类型将犯罪相加并将其放入文件中。我有第一部分,它确实访问了文件并按类型将犯罪金额相加,但是当我打开创建的文件时,它没有正确打印出来,我似乎找不到问题所在。

这是在文件上打印的内容:

¬í sr java.util.HashMapÚÁÃ'Ñ F loadFactorI thresholdxp?@ w
t Violent Crimes Totalsr java.lang.Integerâ ¤÷‡8 I valuexr java.lang.Number†¬•"à‹ xp ¤Mt Rapesq ~ jt 车辆盗窃 ~ {™t 严重袭击 ~ kƒt 凶杀 ~ t 抢劫 ~ N t 非住宅入室盗窃 ~ kÿt 住宅入室盗窃 ~ ã~t 财产犯罪 总计 ~ ïit 盗窃sq ~ :cx

使用system.out.println,它可以打印:

{暴力犯罪总数=42061,强奸=1898,车辆盗窃=97177,严重袭击=27523,

凶杀=399,抢劫=19981,非住宅入室盗窃=27647,住宅入室盗窃=58238,财产犯罪总数=454505,盗窃=342627}

系统打印输出是我想在文件中显示的内容。

public class CSVReader {
public static void main(String[] args) throws FileNotFoundException {
String csvFile = "C:\Users\Cassie\Desktop\mod04_dataset.csv";
BufferedReader br = null;
String line = "";
String cvsSplitBy = ",";
HashMap<String, Integer> map = new HashMap<>();
try {
br = new BufferedReader(new FileReader(csvFile));
br.readLine();
while ((line = br.readLine()) != null) {
String[] data = line.split(cvsSplitBy);
System.out.println(data[2] + " " + data[3]);
if (map.containsKey(data[2])) {
Integer a = map.get(data[2]);
map.put(data[2], a + Integer.parseInt(data[3]));
}
else {
map.put(data[2], Integer.parseInt(data[3]));
}
} 
FileOutputStream f = new 
FileOutputStream("hashmap.ser");  
ObjectOutputStream s = new ObjectOutputStream(f);          
s.writeObject(map);
System.out.println(map);
s.close();
f.close();

} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {       
if (br != null) {
try {
br.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}

当你调用System.out.println(map);时,你会看到map.toString()的结果。如果这是您想要在文件中包含的内容,则可以这样做:

FileOutputStream f = new FileOutputStream("hashmap.ser");  
f.write(map.toString().getBytes());
System.out.println(map);
f.close();

你应该使用 PrintWriter,因为 nö 你正在输出二进制数据

最新更新