您的位置:首页 > 移动开发

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

2017-08-04 10:15 1501 查看
问题: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
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: