文件是否修改"/>
java判断文件是否修改
在正规的网站下在文件的时候,有一个MD5值
import org.apachemons.codec.binary.Hex;
import org.apachemons.codec.digest.DigestUtils;
import org.junit.Assert;
import org.junit.Before;
import org.junit.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;
/**
* Created by moziqi on 15-4-23.
* 消息摘要编码测试
*
* 文件为xxx
* 存储路径目录
* MD5值为xxxx
*
*/
public class MD5Test {
//文件路径
private String path = "";
//MD5值
private String md5 = "";
@Before
public void init() {
path = "";
md5 = "";
}
@Test
public void testByMessageDisgest() {
//构建文件输入流
FileInputStream fileInputStream = null;
try {
fileInputStream = new FileInputStream(new File(path));
try {
//初始化MessageDigest,并指定MD5算法
DigestInputStream digestInputStream = new DigestInputStream(fileInputStream, MessageDigest.getInstance("MD5"));
//流缓冲大小
int buf = 1024;
//缓冲字节数组
byte[] buffer = new byte[buf];
//当读到值大于-1就继续读
try {
int read = digestInputStream.read(buffer, 0, buf);
while (read > -1) {
read = digestInputStream.read(buffer, 0, buf);
}
//获得MessageDigest
MessageDigest messageDigest = digestInputStream.getMessageDigest();
//摘要处理
byte[] bytes = messageDigest.digest();
//十六进制转换
String md5Hex = Hex.encodeHexString(bytes);
Assert.assertEquals(md5Hex, md5);
} catch (IOException e) {
e.printStackTrace();
}
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} finally {
try {
if (fileInputStream != null) {
//关闭流
fileInputStream.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
@Test
public void testByDigestUitls() {
//构建文件输入流
FileInputStream fileInputStream = null;
try {
//构建文件输入流
fileInputStream = new FileInputStream(new File(path));
try {
String md5Hex = DigestUtils.md5Hex(fileInputStream);
Assert.assertEquals(md5Hex, md5);
} catch (IOException e) {
e.printStackTrace();
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} finally {
//关闭流
try {
if (fileInputStream != null) {
//关闭流
fileInputStream.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
更多推荐
java判断文件是否修改
发布评论