废话不多说,直接上代码,整理你杂乱单词的必备干货
package com.hp.word;
import java.io.*;
import java.util.TreeMap;
import java.util.Map;
public class Sort2 {
// 定义一个Treemap集合
private static TreeMap words = new TreeMap(
String.CASE_INSENSITIVE_ORDER);
// String.CASE_INSENSITIVE_ORDER 忽略大小写
private static void sort() throws IOException {
File f = new File("e:\word.txt");
// 装饰模式
BufferedReader reader = new BufferedReader(new InputStreamReader(
new FileInputStream(f)));
// 单词
String word = null;
// 如果读取的这一行不为空的话
while ((word = reader.readLine()) != null) {
//判断是否存在键所对应的值,即判断是否有重复单词
if (words.containsKey(word))
words.put(word, words.get(word) + 1);
else
words.put(word, 1);
}
reader.close();
//排序后写入
outFile(f);
}
private static void outFile(File f) throws FileNotFoundException,
IOException {
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(
new FileOutputStream(f)));
for (Map.Entry item : words.entrySet()) {
writer.write(item.getKey() + "t" + judge(item.getValue()));
writer.newline();
}
writer.close();
}
public static String judge(Integer number) {
int n = number;
if (n < 2) {
return " ";
} else {
return number + "";
}
}
public static void main(String args[]) throws IOException {
sort();
System.out.println("成功");
}
} 


