Program to demonstrate how to access Temporary Directory and delete its files through a Java program.
package com.hubberspot.example;
import java.io.File;
public class TemporaryDirectory {
public static void main(String[] args) {
// 1. Create a Properties refernce pointing to
// System.getproperties() as this method returns all
// the System properties
java.util.Properties properties = System.getProperties();
// 2. System class has a property by name "java.io.tmpdir"
// which returns String which is the name of the location
// of temp directory. See the output for my machine's temp
// directory
System.out.println(properties.getProperty("java.io.tmpdir"));
String tempFileName = properties.getProperty("java.io.tmpdir");
// 3. Create a File object which will point to this temp
// directory.
File directory = new File(tempFileName);
// 4. Get all files in directory using the method listFiles()
File[] files = directory.listFiles();
// 5. Loop through each file and call delete() on it
for (File file : files)
{
// 6. This will loop each file/directory and delete file
file.delete();
// 7. If it cannot delete the file it prints the name
// of file it cant delete
if (!file.delete())
{
System.out.println("Failed to delete "+file);
}
}
}
}
Output of the program :
