在学习专业英语的时候,喜欢使用world记录单词对应的中文翻译,
如下图:
但是发现会存在重复的单词,于是便想到使用Java中的Map集合的特性完成单词去重的任务。
主要步骤:
1.使用Scanner将文件的每一行读入并保存在字符串中;
2.将字符串拆分成中文和英文两个部分;
3.中文部分作为Map集合的key,英文部分作为相应的value;
4.将Map集合的数据使用printWriter打印流重新写回数据,即可完成单词的去重。
代码示例
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;
import java.util.Iterator;
public class Main{
public static void main(String [] args) throws IOException{
// 处理文件
File infile = new File("/home/linyimin//DaSi/学习/软件工程.txt");
// 输出文件
InputStream in = new FileInputStream(infile);
File outfile = new File("/home/linyimin//DaSi/学习/软件工程_out.txt");
FileOutputStream out = new FileOutputStream(outfile);
// 使用打印流完成向文件写入数据
PrintWriter tool = new PrintWriter(out);
// 使用Scanner完成从文件中读取数据
Scanner cin = new Scanner(in);
// 一次读取一行
cin.useDelimiter("\n");
// 使用HashMap完成去重任务
Map<String, String> map = new HashMap<String, String>();
while(cin.hasNext()){
String str = cin.next();
// 将每行数据读入,根据多个空格为特征,切分字符串
// 中文为Map中的key,对应英文为vaule,存入Map集合中
String [] str1 = str.split("\\s+", 2);
if(str1.length > 1){
map.put(str1[0], str1[1] );
}
}
// 将Map集合转换成Set集合,Set集合使用Iterator进行迭代输出
Iterator <Map.Entry<String, String>> iter = map.entrySet().iterator();
while(iter.hasNext()){
Map.Entry<String, String> m = iter.next();
String chinese = m.getKey(); // 从Map.Entry对象中取出key值
String english = m.getValue(); // 从Map.Entry对象中取出value值
// 使用PrintWriter向文件中写入去重之后的数据
tool.println(chinese + " " + english);
}
// 关闭资源
cin.close();
in.close();
tool.close();
}
}