关于MappedByteBuffer占用内存和文件关闭

问题:MappedByteBuffer内存占用和文件关闭等不确定问题,被MappedByteBuffer打开的文件只有在垃圾收集时才会被关闭。

业务场景

定时任务:操作文件

scheduExec.scheduleWithFixedDelay(new CreateCPWordToFSExecutorTask(), 0, PERIOD_DAY, TimeUnit.MILLISECONDS);//(按推迟时间间隔执行)


CreateCPWordToFSExecutorTask类中获取文件的

FileMD5 md5 = new FileMD5();
sysFileParam.put("MD5", md5.getMd5ByFile(file));


问题代码 注释段

package com.qware.iot.utils;



import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.math.BigInteger;
import java.nio.MappedByteBuffer;
import java.nio.channels.FileChannel;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;


/**
 * @ClassName: FileMD5
 * @Description: 文件的MD5
 * @author: zcj
 * @date: 2017年5月19日 下午2:59:21
 */
public class FileMD5 {
/**

* @Title: getMd5ByFile
* @Description: MappedByteBuffer可以提高效率,但也存在一些问题,主要就是内存占用和文件关闭等不确定问题,
* 被MappedByteBuffer打开的文件只有在垃圾收集时才会被关闭。。。
* @param file
* @return
* @return: String
*/
public String getMd5ByFile(File file) {
String value = null;
FileInputStream inputStream = null;
FileChannel inFileChannel = null;
try {
inputStream = new FileInputStream(file);
inFileChannel = inputStream.getChannel();
//MappedByteBuffer byteBuffer = inFileChannel.map(FileChannel.MapMode.READ_ONLY, 0, file.length());
MessageDigest md5 = MessageDigest.getInstance("MD5");
byte[] byteBuffer = new byte[1024];
int length = -1;
while ((length = inputStream.read(byteBuffer, 0, 1024)) != -1) {
md5.update(byteBuffer, 0, length);
}
//md5.update(byteBuffer);
BigInteger bi = new BigInteger(1, md5.digest());
value = bi.toString(16);
} catch (Exception e) {
e.printStackTrace();
}finally {
if (null != inFileChannel) {
try {
inFileChannel.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (null != inputStream) {
try {
inputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
return value.toLowerCase();
}

}


执行备注是代码异常:java.io.FileNotFoundException: D:\test\档案卡_20170619.doc (请求的操作无法在使用用户映射区域打开的文件上执行。)



参考:http://langgufu.iteye.com/blog/2107023

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值