java生成临时文件并删除

import java.io.File;

public class FileDemo {
   public static void main(String[] args) {
      File f = null;           
      try{
         // creates temporary file
         f = File.createTempFile("tmp", ".txt");
         
         // prints absolute path
         System.out.println("File path: "+f.getAbsolutePath());
         
         // deletes file when the virtual machine terminate
          f.deleteOnExit();
         
         // creates temporary file
         f = File.createTempFile("tmp", null);
         
         // prints absolute path
         System.out.print("File path: "+f.getAbsolutePath());
         
         // deletes file when the virtual machine terminate
         f.deleteOnExit();
         
      }catch(Exception e){
         // if any error occurs
         e.printStackTrace();
      }
   }
}

 

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
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虚拟机的堆内存空间,因此在处理大文件时应谨慎使用,避免内存溢出的情况发生。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值