
In this tutorial, we will create a temp directory and a file and delete them when the application terminates.
We have made use of the Files.createTempDirectory and Files.createTempFile to create a temporary directory and file respectively with a prefix and a random number that's added by the Java native logic!
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;
public class JavaTempFileAndDirExample {
private static Path tempDirPath;
private static Path tempFilePath;
public static void main(String[] args) throws InterruptedException, IOException {
String pathStr = "/Users/code2care/my-projects-22/java-examples/";
Path dirPathAndName = Paths.get(pathStr);
try {
//Step 1: Create Temp Directory
tempDirPath = Files.createTempDirectory(dirPathAndName, "temp_");
System.out.println("Temp Directory created: " + tempDirPath);
//Step 2: Create Temp File
tempFilePath = Files.createTempFile(tempDirPath, "temp_file_", ".txt");
System.out.println("Temp File created: " + tempFilePath);
//Step 3: Write some text to file
Files.write(tempFilePath, "Hello".getBytes(), StandardOpenOption.APPEND);
//Step 4: Do some logic!
Thread.sleep(5000);
//Step 5: Delete temp file
Files.delete(tempFilePath);
System.out.println("Temp file deleted..");
//Step 6: Delete temp directory
Files.delete(tempDirPath);
System.out.println("Work done deleting temp dir:" + tempDirPath);
} catch (IOException e) {
System.out.println("Error occurred while creating Directories!...");
e.printStackTrace();
}
}
}
Output:
Temp Directory created: /Users/code2care/my-projects-22/java-examples/temp_732237094777468206
Temp File created: /Users/code2care/my-projects-22/java-examples/temp_7322370947774682067/temp_file_5923746658607316240.txt
Temp file deleted..
Work done deleting temp dir:/Users/code2care/my-projects-22/java-examples/temp_7322370947774682067
This logic can be extended to create multiple temporary files and directories. Make sure to delete all the files within the directory before you delete the directory or else you will get SecurityException.
Have Questions? Post them here!
- Add two numbers using Java Generics
- Convert Java List to Json String using Jackson
- Convert Java Object to JSON using Jackson Library
- Java SE JDBC: Insert with PreparedStatement Example
- [Program] How to read three different values using Scanner in Java
- Java JDBC Batch Update Example with PreparedStatement
- Java Stream flatmap() Examples
- Save Java Object as JSON file using Jackson Library
- Java get day of the week as an int using DayOfWeek
- Create Nested Directories using Java Code
- Java JDBC Delete a Record in Database Table using PreparedStatement
- List of jars required for Struts2 project
- Convert Java Object to XML using Jackson Library
- Struts2 : java.lang.ClassNotFoundException: org.apache.commons.fileupload.RequestContext
- Java JDBC Get Id of the Inserted Record with AutoIncrement
- How to list all tables using Java JDBC
- Java Jackson ObjectMapper Class with Examples
- Fix: Maven - Failed to execute goal - Compilation failure - Source/Target option 5 is no longer supported. Use 7 or later
- Eclipse : The type java.lang.CharSequence cannot be resolved. Indirectly referenced from required .class files
- Formatting Double in Java [Examples]
- How to run Java Unit Test cases with Apache Maven?
- [fix] NullPointerException Cannot Invoke findById because Repository is null - Java Spring
- [Fix] java: integer number too large compilation error
- [Java] Read a File with UTF-8 Encoding
- How to detect Operating System using Java code
- How to Enable or Disable Dark Mode on macOS Ventura 13 - MacOS
- Rounded Images in Bootstrap framework - Bootstrap
- Sharepoint Server 2016 installation Prerequisites with download links - SharePoint
- How to display date and time in GMT Timezone in Java - Java
- Quick Steps to install NodeJs on macOS - MacOS
- How to Generate Self-Signed OpenSSL certificate in three easy steps - HowTos
- Spotify is down for iOS and Android globally - error no internet connection available, something went wrong - News
- Understanding grep command and its usage [Unix/Linux/macOS/Windows-Bash] - HowTos