下载文件操作时,临时文件的处理可能是经常会碰到却又很容易忽略的问题,如果不仔细处理,很容易在服务器上遗留一堆的临时文件。
一般我们可能会这样做(在Struts2下的代码,其它环境也类似):
// 下载文件
try {
stream = new FileInputStream(new File(downloadFile));
FileUtil.deleteFile(downloadFile);
} catch (Exception e) {
log.error("系统错误" + e.getMessage());
throw new Exception(e.getMessage());
}
然而,虽然写了 FileUtil.deleteFile(downloadFile);, 这句话却不能起任何作用,因为前面的Stream没有关闭,无法Delete。
为此,增加了一下函数。
public static InputStream getDownloadFile(String realPath, byte[] fileContents) throws Exception {
// 初始化Stream
InputStream stream = null;
// 判断参数
if (realPath == null && fileContents == null) {
throw new Exception("not found stream Contents");
}
// 处理模式判断
if (realPath != null && !"".equals(realPath)) {
// 文件模式
try {
// 读取文件到二进制中
File readFile = new File(realPath);
FileInputStream fis = new FileInputStream(readFile);
// 读取
byte[] buffer = new byte[(int)readFile.length()];
fis.read(buffer);
// 关闭
fis.close();
stream = new ByteArrayInputStream(buffer);
} catch (FileNotFoundException e) {
throw e;
}
} else {
// 字节数组模式
stream = new ByteArrayInputStream(fileContents);
}
return stream;
}
代码也改为:
// 下载文件
try {
stream = FileUtil.getDownloadFile(downloadFile, null);
FileUtil.deleteFile(downloadFile);
} catch (Exception e) {
log.error("系统错误" + e.getMessage());
throw new Exception(e.getMessage());
}
即可正确的删除临时文件。