Home > Java > javaTutorial > Temporary files in Java

Temporary files in Java

WBOY
Release: 2023-09-23 19:37:02
forward
755 people have browsed it

Temporary files in Java

In some scenarios, such as unit testing, or some application logic, you may need to create temporary files.

Create temporary files

The File class in Java provides a method named createTempFile(). This method accepts two String variables representing the prefix (starting name) and suffix (extension) of the temporary file and a File object representing the directory (abstract path) where the file needs to be created.

Example

The following Java example creates a temporary file named exampleTempFile5387153267019244721.txt in the path D:/SampleDirectory

import java.io.File;
import java.io.IOException;
public class TempararyFiles {
   public static void main(String args[]) throws IOException {
      String prefix = "exampleTempFile";
      String suffix = ".txt";
      //Creating a File object for directory
      File directoryPath = new File("D:/SampleDirectory");
      //Creating a temp file
      File.createTempFile(prefix, suffix, directoryPath);
      System.out.println("Temp file created.........");
   }
}
Copy after login

Output

Temp file created.........
Copy after login

Delete temporary files

The File class provides the delete() method, which can delete the current file or directory and call this method on the temporary file.

Example

The following Java program creates and deletes temporary files.

import java.io.File;
import java.io.IOException;
public class TempararyFiles {
   public static void main(String args[]) throws IOException {
      String prefix = "exampleTempFile";
      String suffix = ".txt";
      //Creating a File object for directory
      File directoryPath = new File("D:/SampleDirectory");
      //Creating a temp file
      File tempFile = File.createTempFile(prefix, suffix, directoryPath);
      System.out.println("Temp file created: "+tempFile.getAbsolutePath());
      //Deleting the file
      tempFile.delete();
      System.out.println("Temp file deleted.........");
   }
}
Copy after login

Output

Temp file created: D:\SampleDirectory\exampleTempFile7179732984227266899.txt
Temp file deleted.........
Copy after login

The above is the detailed content of Temporary files in Java. For more information, please follow other related articles on the PHP Chinese website!

source:tutorialspoint.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template