2. 用代码实现以下需求 (1)有如下字符串"If you want to change your fate I think you must come to the dark horse to learn java"(用空格间隔) (2)打印格式: to=3 think=1 you=2 //........ (3)按照上面的打印格式将内容写入到D:\\count.txt文件中(要求用高效流)
package exrcise;
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Map.Entry;
import java.util.Set;
public class Demo2 {
/*
* 2. 用代码实现以下需求
(1)有如下字符串"If you want to change your fate I think you must come to the dark horse to learn java"(用空格间隔)
(2)打印格式:
to=3
think=1
you=2
//........
(3)按照上面的打印格式将内容写入到D:\\count.txt文件中(要求用高效流)
*
* */
public static void main(String[] args) {
HashMap<String, Integer> map = function_1();
// //复习一下遍历map
// //keySet
// for (String key : map.keySet()) {
// System.out.println(key + ":" + map.get(key));
// }
// //用entrySet
// Set<Entry<String, Integer>> set = map.entrySet();
// for (Entry<String, Integer> entry : set) {
// System.out.println(entry.getKey() + ":" + entry.getValue());
// }
//iterator 1
// Set<String> set = map.keySet();
// Iterator<String> it = set.iterator();
// while (it.hasNext()) {
// String key = it.next();
// System.out.println(key + "=" + map.get(key));
// }
//iterator 2
// Set<Entry<String, Integer>> set = map.entrySet();
// Iterator<Entry<String, Integer>> it = set.iterator();
// while (it.hasNext()) {
// String key = it.next().getKey();
// System.out.println(key + "=" + map.get(key));
// }
bufWrite(map, "/home/alex/test/count.txt");
}
private static void bufWrite(HashMap<String, Integer> map, String dest) {
BufferedWriter bufw = null;
try {
for(String key : map.keySet()) {
System.out.println(key + "=" + map.get(key));
//不要忘记在FileWriter中添加append参数,不然每次遍历写入都是重写文件。
bufw = new BufferedWriter(new FileWriter(dest, true));
bufw.write(key + "=" + map.get(key));
bufw.newLine();
bufw.flush();
}
} catch (IOException e) {
e.printStackTrace();
}finally {
try {
bufw.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
private static HashMap<String, Integer> function_1() {
String str = "If you want to change your fate I think you must come to the dark horse to learn java";
HashMap<String, Integer> map = new HashMap<>();
String[] strs = str.split(" ");
for (int i = 0; i < strs.length; i++) {
String key = strs[i];
Integer value = 1;
if(!map.containsKey(key)) {
map.put(key, value);
}else {
value = map.get(key);
map.put(key, value+1);
}
}
return map;
}
}