How to deal with temporary files in Java which gracefully

background

Recently I took over the codes colleagues found him to be so treated excel file:

1. 将文件保存到一个事先定义好的目录;如果目录不存在则新建
2. 使用excel处理工具根据文件路径读取文件内容之后处理业务逻辑
3. 编写一个定时任务每天凌晨1点删除该目录内的.xlsx文件
复制代码

Although this can be effective, but it is extremely complicated, very elegant. In fact jdk in the provision of handling temporary files method (Temporary File), and now let's take a look.

Create a temporary file

There are many scenes to create a temporary file in java, but most are in unit testing or uploaded files for content processing. When the test case or file processing is complete, you do not care whether the file still exists. Moreover, continued accumulation of invalid documents will no doubt waste a lot of disk space.

Create a temporary file by using java.io.File.createTempFile ()

public class TemporaryFileExample
{
   public static void main(String[] args)
   {
      File temp;
      try
      {
         temp = File.createTempFile("myTempFile", ".txt");
          
         System.out.println("Temp file created : " + temp.getAbsolutePath());
      } catch (IOException e)
      {
         e.printStackTrace();
      }
   }
}
复制代码

windows system output: C: \ Users \ admin \ AppData \ Local \ Temp \ myTempFile7295261447112135643.txt

Create temporary files by using the NIO

public class TemporaryFileExample
{
   public static void main(String[] args)
   {
      try
      {
         final Path path = Files.createTempFile("myTempFile", ".txt");
         System.out.println("Temp file : " + path);

          
      } catch (IOException e)
      {
         e.printStackTrace();
      }
   }
}
复制代码

windows system output: C: \ Users \ admin \ AppData \ Local \ Temp \ myTempFile3492283537103788196.txt

Write temporary files

For example, when the file upload, we can write temporary files among a stream of bytes.

Use java.io.BufferedWriter write temporary files

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
 
public class TemporaryFileExample
{
   public static void main(String[] args)
   {
      File temp;
      try
      {
         temp = File.createTempFile("myTempFile", ".txt");
 
         BufferedWriter bw = new BufferedWriter(new FileWriter(temp));
         bw.write("This is the temporary data written to temp file");
         bw.close();
 
         System.out.println("Written to Temp file : " + temp.getAbsolutePath());
      } catch (IOException e)
      {
         e.printStackTrace();
      }
   }
}
复制代码

Use NIO write temporary files

If you want to use java NIO library, you can use Files.write () method

public class TemporaryFileExample
{
   public static void main(String[] args)
   {
      try
      {
         final Path path = Files.createTempFile("myTempFile", ".txt");
         System.out.println("Temp file : " + path);
 
 
         byte[] buf = "some data".getBytes();
         Files.write(path, buf);
 
      } catch (IOException e)
      {
         e.printStackTrace();
      }
   }
}
复制代码

Delete Temporary Files

Delete temporary files is a very important step, because you do not want your disk space explosion. To delete files when the application exit (jvm terminated), you can use:

File temp = File.createTempFile("myTempFile", ".txt");
temp.deleteOnExit();
复制代码

Or if you want to immediately delete the file, you can use the direct delete()method

File temp = File.createTempFile("myTempFile", ".txt");
temp.delete();
复制代码

Use IO delete temporary files

import java.io.File;
import java.io.IOException;
 
public class TemporaryFileExample
{
   public static void main(String[] args)
   {
      File temp;
      try
      {
         temp = File.createTempFile("myTempFile", ".txt");
          
         System.out.println("Temp file created : " + temp.getAbsolutePath());
          
         //temp.delete(); //立即删除
          
         temp.deleteOnExit(); //运行结束时删除
          
         System.out.println("Temp file exists : " + temp.exists());
      } catch (IOException e)
      {
         e.printStackTrace();
      }
   }
}
复制代码

Delete temporary files using the NIO

public class TemporaryFileExample
{
   public static void main(String[] args)
   {
      try
      {
         final Path path = Files.createTempFile("myTempFile", ".txt");
         System.out.println("Temp file : " + path);
 
        // Files.delete(path);  //立即删除文件
        
        Files.deleteIfExists(path);
          
         
          
      } catch (IOException e)
      {
         e.printStackTrace();
      }
   }
}
复制代码

Guess you like

Origin juejin.im/post/5d142f4de51d45777621bbbe