整理你杂乱单词的必备代码干货
废话不多说,直接上代码,整理你杂乱单词的必备干货
package com.hp.word;
import java.io.*;
import java.util.TreeMap;
import java.util.Map;
/**
* 排序单词
*
* @author Administrator
*资料: http://wenda.so.com/u/1901333518
*/
public class Sort2 {
// 定义一个Treemap集合
private static TreeMap<String, Integer> words = new TreeMap<String, Integer>(
String.CASE_INSENSITIVE_ORDER);
// String.CASE_INSENSITIVE_ORDER 忽略大小写
/**
* 单词排序并且计算重复
*
* @throws IOException
*/
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);
}
/**
* 重新写入文件,并且计算值
* @param f
* @throws FileNotFoundException
* @throws IOException
*/
private static void outFile(File f) throws FileNotFoundException,
IOException {
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(
new FileOutputStream(f)));
for (Map.Entry<String, Integer> item : words.entrySet()) {
writer.write(item.getKey() + "\t" + judge(item.getValue()));
writer.newLine();
}
writer.close();
}
/**
* 判断次数是否大于2
* @param number
* @return
*/
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("成功");
}
}
点击查看更多内容
22人点赞
评论
共同学习,写下你的评论
评论加载中...
作者其他优质文章
正在加载中
感谢您的支持,我会继续努力的~
扫码打赏,你说多少就多少
赞赏金额会直接到老师账户
支付方式
打开微信扫一扫,即可进行扫码打赏哦