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

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

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

 

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Java中生成临时文件并不一定要将其写入硬盘,可以选择将其写入内存中。 通常情况下,我们可以使用`java.nio.file.Files`类提供的`createTempFile`方法来生成临时文件。该方法会在默认的临时文件目录中创建一个新的临时文件,并返回其路径。 如果希望将临时文件写入内存,可以使用Java的内存映射文件(MappedByteBuffer)来实现。内存映射文件是一种将磁盘文件直接映射到内存的技术,可以在不进行文件I/O的情况下访问文件数据。 首先,我们可以使用`java.nio.file.Files`类提供的`createTempFile`方法来创建一个临时文件。然后,我们可以使用`java.nio.channels.FileChannel`类的`map`方法将该临时文件映射到内存中的`MappedByteBuffer`对象。 以下是一个简单的示例代码: ```java import java.io.IOException; import java.nio.ByteBuffer; import java.nio.MappedByteBuffer; import java.nio.channels.FileChannel; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.StandardOpenOption; public class TempFileInMemoryExample { public static void main(String[] args) { try { Path tempFilePath = Files.createTempFile("temp", ".txt"); // 将临时文件映射到内存中 FileChannel fileChannel = FileChannel.open(tempFilePath, StandardOpenOption.READ, StandardOpenOption.WRITE); MappedByteBuffer mappedByteBuffer = fileChannel.map(FileChannel.MapMode.READ_WRITE, 0, fileChannel.size()); // 向内存中的映射文件写入数据 String data = "Hello, World!"; byte[] bytes = data.getBytes(); mappedByteBuffer.put(bytes); // 读取内存中的映射文件数据 mappedByteBuffer.flip(); byte[] readBytes = new byte[bytes.length]; mappedByteBuffer.get(readBytes); String readData = new String(readBytes); System.out.println(readData); // 关闭文件通道 fileChannel.close(); // 删除临时文件 Files.delete(tempFilePath); } catch (IOException e) { e.printStackTrace(); } } } ``` 在上述代码中,首先创建了一个临时文件,然后将其映射到内存中的`MappedByteBuffer`对象。接着,我们可以向映射文件写入数据,并从中读取数据。最后,关闭文件通道并删除临时文件。 需要注意的是,映射文件将会占用Java虚拟机的堆内存空间,因此在处理大文件应谨慎使用,避免内存溢出的情况发生。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值