background

I recently took over my colleague’s code and noticed that he handled Excel files like this:

1. Save the file to a predefined directory. If the directory does not exist, create one. 2. Use the Excel processing tool to read the file content according to the file path and process the service logic. Write a scheduled task to delete the.xlsx files in this directory at 1 a.m. every dayCopy the code

This can work, but it is extremely tedious and very inelegant. The JDK already provides methods for handling Temporary files, so let’s take a look.

Create temporary files

There are many scenarios for creating temporary files in Java, but most involve unit testing or content manipulation of uploaded files. When the test case or file is processed, you don’t care if the file still exists. And the constant accumulation of invalid files can certainly waste a lot of disk space.

Through the use of Java. IO. File. CreateTempFile () to create temporary File

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(); }}}Copy the code

Windows in the system output: C: \ Users \ admin \ AppData \ Local \ Temp \ myTempFile7295261447112135643 TXT

Create temporary files by using 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(); }}}Copy the code

Windows in the system output: C: \ Users \ admin \ AppData \ Local \ Temp \ myTempFile3492283537103788196 TXT

Write to temporary file

For example, when a file is uploaded, we can write the byte stream to a temporary file.

Use java.io.BufferedWriter to 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(); }}}Copy the code

Write temporary files using NIO

If you want to use the Java NIO library, you can use the 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(); }}}Copy the code

Deleting temporary Files

Deleting temporary files is a very important step because you don’t want your disk space to explode. To delete files when exit is applied (JVM terminates), you can use:

File temp = File.createTempFile("myTempFile".".txt");
temp.deleteOnExit();
Copy the code

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

File temp = File.createTempFile("myTempFile".".txt");
temp.delete();
Copy the code

Delete temporary files using IO

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(); // Delete immediately
          
         temp.deleteOnExit(); // Delete at the end of the run
          
         System.out.println("Temp file exists : " + temp.exists());
      } catch(IOException e) { e.printStackTrace(); }}}Copy the code

Use NIO to delete temporary files

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); // Delete the file immediately
        
        Files.deleteIfExists(path);
          
         
          
      } catch(IOException e) { e.printStackTrace(); }}}Copy the code