
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.
Provide Feedback For This Article
We take your feedback seriously and use it to improve our content. Thank you for helping us serve you better!
😊 Thanks for your time, your feedback has been registered!
Comments & Discussion
Facing issues? Have questions? Post them here! We're happy to help!