java判断文件是否修改

编程入门 行业动态 更新时间:2024-10-11 13:30:54

java判断<a href=https://www.elefans.com/category/jswz/34/1771438.html style=文件是否修改"/>

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判断文件是否修改

本文发布于:2024-03-10 09:46:11,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1727631.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:文件   java

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!