我的问题是我觉得既然需要摘要流处理文件,那么应该din.getMessageDigest().digest()去获得摘要,但是MessageDigest的对象的digest()也可以得到相同的结果,那为什么还需要DigestInputStream摘要流。从代码可以看到mg.digest();取得了摘要,那摘要流岂不是白read()了,谢谢
package test;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.security.DigestInputStream;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
public class FileDigestThread extends Thread{
private File input;
public FileDigestThread(File input){
this.input = input;
}
public void run(){
try {
FileInputStream fs = new FileInputStream(input);
MessageDigest mg = MessageDigest.getInstance("SHA");
DigestInputStream din = new DigestInputStream(fs,mg);
/* while
((b=din.read())!=-1);*/
while(true){
if(din.read()==-1);
break;
}
din.close();
// byte[] digest = din.getMessageDigest().digest();
byte[] digest = mg.digest();
StringBuffer result = new StringBuffer(input.toString());
result.append(": ");
for(int i =0;i<digest.length;i++)
{
result.append(digest[i]+ "");
}
System.out.println("result: "+result);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (NoSuchAlgorithmException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
for(int i = 0;i<args.length;i++)
{
File f = new File(args[i]);
Thread thread = new FileDigestThread(f);
thread.start();
}
}
}
------解决方案--------------------
mg和din.getMessageDigest()是相同的。din只是包装,java的对象都是引用,还不理解为什么相同,就仔细学习一下引用。