1 import java.io.BufferedWriter; 2 import java.io.FileWriter; 3 import java.io.IOException; 4 import java.util.HashMap; 5 import java.util.Map; 6 7 public class mapfor { 8 9 10 public static void main(String[] args) throws IOException { 11 Map<String, Integer> mp = new HashMap<>(); 12 mp.put("张三", 20); 13 mp.put("李四", 21); 14 mp.put("王二", 22); 15 mp.put("李五", 23); 16 //创建字符缓冲输出流对象,构造方法中绑定字符输出流 17 BufferedWriter bw = new BufferedWriter(new FileWriter("10_IO\\789.txt")); 18 19 String line; 20 //遍历HashMap集合,获取每一个键值对 21 for (String key : mp.keySet()) {//相当于set<String> ks=mp.keySet();mp.keySet()是所有键的集合 22 23 Integer value = mp.get(key); 24 // System.out.println(key+"="+value); 25 line = key+"="+value; 26 bw.write(line); 27 bw.newLine();//每次输出时换行 28 29 // System.out.println(key + "=" + mp.get(key)); 30 } 31 bw.close(); 32 } 33 34 }