java判断文件是否相同的方法

Java高级开发 判断 402浏览 5评论

//计算文件的MD5值根据MD5值判断文件是否是同一个文件publicstaticStringgetFileMD5(Filefile){if(!file.isFile()){returnnull;}Mess**eDigestdigest=null;FileInputStreamin=null;bytebuffer[]=newbyte[8192];intlen;try{digest=Mess**eDigest.getInstance("MD5");in=newFileInputStream(file);while((len=in.read(buffer))!=-1){digest.update(buffer,0,len);}BigIntegerbigInt=newBigInteger(1,digest.digest());returnbigInt.toString(16);}catch(Exceptione){e.printStackTrace();returnnull;}finally{try{in.close();}catch(Exceptione){e.printStackTrace();}}}

//计算文件的SHA-1值根据SHA-1值判断文件是否是同一个文件publicstaticStringgetFileSha1(Filefile){if(!file.isFile()){returnnull;}Mess**eDigestdigest=null;FileInputStreamin=null;bytebuffer[]=newbyte[8192];intlen;try{digest=Mess**eDigest.getInstance("SHA-1");in=newFileInputStream(file);while((len=in.read(buffer))!=-1){digest.update(buffer,0,len);}BigIntegerbigInt=newBigInteger(1,digest.digest());returnbigInt.toString(16);}catch(Exceptione){e.printStackTrace();returnnull;}finally{try{in.close();}catch(Exceptione){e.printStackTrace();}}}

publicclassIOOperation{publicstaticvoidmain(String[]args){FileInputStreamFile1=null;FileInputStreamFile2=null;BufferedReaderin=null;StringsFile;if(args.length!=2){System.out.println("Thecommandlineshouldbe:javaIOOperationtestX.txttestX.txt");System.out.println("Xshouldbeoneofthearray:1,2,3");System.exit(0);}try{File1=newFileInputStream(args[0]);File2=newFileInputStream(args[1]);try{if(File1.available()!=File2.available()){//长度不同内容肯定不同System.out.println(args[0]+"isnotequalto"+args[1]);}else{booleant**=true;while(File1.read()!=-1&&File2.read()!=-1){if(File1.read()!=File2.read()){t**=false;break;}}if(t**==true)System.out.println(args[0]+"equalsto"+args[1]);elseSystem.out.println(args[0]+"isnotequalto"+args[1]);}}catch(IOExceptione){System.out.println(e);}}catch(FileNotFoundExceptione){System.out.println("Filecan'tfind..");}finally{try{if(File1!=null)File1.close();if(File2!=null)File2.close();}catch(IOExceptione){System.out.println(e);}}}

以上就是java判断文件是否相同的方法的详细内容,更多请关注php中文网其它相关文章!

本文原创发布php中文网,转载请注明出处,感谢您的尊重!