ITeye博客

下载文件时,你有没有考虑临时文件已经一大堆了?

penua · 2009-01-12 17:51 · Java应用 · 企业架构 · Markdown

下载文件操作时,临时文件的处理可能是经常会碰到却又很容易忽略的问题,如果不仔细处理,很容易在服务器上遗留一堆的临时文件。

一般我们可能会这样做(在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());
		}

 

 即可正确的删除临时文件。

评论(8)

  1. #8 楼 · zds625 · 2009-01-21 16:28

    在struts2实现上传的时候也会保存文件到临时目录,但是这个目录临时文件不会删除,不知大家是定时做删除处理还是怎样做呢?

  2. #7 楼 · sdh5724 · 2009-01-14 21:03

    哈, DZ, 连G点。。。。

  3. #6 楼 · gembler · 2009-01-14 19:14

    sdh5724出爆击···哈哈

  4. #5 楼 · sdh5724 · 2009-01-14 14:04

    如果你真想彻底, 就在finnaly里去做。

  5. #4 楼 · sdh5724 · 2009-01-14 14:03

    如果你真想彻底, 就在finnaly里去做。

  6. #3 楼 · penua · 2009-01-14 13:24

    谢谢你们意见.

    这确实是很常识性的问题,解决办法也很多, 不过在最近一个项目中,却因为忽略这个问题很久,最终导致临时文件一大堆了, 若没有及时删除, 硬盘随时有可能撑破..

    :lol:

  7. #2 楼 · myy · 2009-01-13 08:56

    这种临时文件完全可以集中放在一个固定目录,用后台的定时程序清理,根据具体情况定策略。

  8. #1 楼 · ariesying · 2009-01-12 23:38

    资源类的东东用完关闭应该是常识的吧。

评论功能维护中,当前仅展示历史评论。