公司笔试题,求高手帮帮吗请写一个程序找出附件中文件重复的行
输出:
输出一个文本文件,给出哪些行是重复的,第一次出现的行号,格式如下
行号 此行的文本内容
并给出此程序的运行时间请Java写一个处理程序
要求代码清晰,易维护,可读性好,执行效率高,如果算法比较复杂请给出适当的算法说明
输出:
输出一个文本文件,给出哪些行是重复的,第一次出现的行号,格式如下
行号 此行的文本内容
并给出此程序的运行时间请Java写一个处理程序
要求代码清晰,易维护,可读性好,执行效率高,如果算法比较复杂请给出适当的算法说明
import java.io.*;public class Test11{
public static void main(String[] args)throws Exception{
long startTime=System.currentTimeMillis();
putListToFile(sameLines("aa.txt"),"result.txt");
long endTime=System.currentTimeMillis();
System.out.println("所用时间:"+(endTime-startTime)+"毫秒");
}
/*用HashMap<String,String>来找出重复行,key 为行,value为行号+行。
*@return 返回一个包含重复行的ArrayList<String>
*/
public static ArrayList<String> sameLines(String fileName) throws Exception{
ArrayList<String> result=new ArrayList<String>();
BufferedReader br=new BufferedReader(new InputStreamReader(new FileInputStream(fileName)));
HashMap<String,String> hm=new HashMap<String,String>();
String line=null; //line in file
String numberLine=null; //line with line number
int count=1; //line number counter
while((line=br.readLine())!=null){
numberLine=hm.get(line);
if(numberLine!=null){
if(!numberLine.substring(0,1).equals("M")){
numberLine="M"+numberLine; //flag a repetitive numberLine with "M"
}
}else{
numberLine=count+" "+line; //every numberLine must start with line number
}
hm.put(line,numberLine);
count++;
}
br.close();
for(Map.Entry<String,String> me:hm.entrySet()){
numberLine=me.getValue();
if(numberLine.substring(0,1).equals("M")){
result.add(numberLine.substring(1)); //remove the flag "M"
}
}
return result;
}
/*把结果写入文件
*/
public static void putListToFile(ArrayList<String> al,String fileName) throws Exception{
BufferedWriter bw=new BufferedWriter(new OutputStreamWriter(new FileOutputStream(fileName)));
for(String str:al){
bw.write(str);
bw.newLine();
}
bw.flush();
bw.close();
}
}代码中的注释如果是中文会破坏格式,所以用了英文,虽然我的英文很烂。
aa.txt:
aaaa
bb bb
cc adf ff
bb bb
aaaa
dsfe
aaaa
bb bb
aaa
bbbb结果:
result.txt:
2 bb bb
1 aaaa测试文件不大,所以控制台输出:
F:\java>java Test11
所用时间:0毫秒