Free Data Structures and Algorithms Course

Subscribe below and get all best seller courses for free !!!


Subscribe to all free courses

How to access Temporary Directory and delete its files through a Java program ?.

Program to demonstrate how to access Temporary Directory and delete its files through a Java program.

package com.hubberspot.example;


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 ""
  // which returns String which is the name of the location
  // of temp directory. See the output for my machine's temp
  // directory

  String tempFileName = properties.getProperty("");

  // 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

   // 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 :

© 2021 Learn Java by Examples Template by Hubberspot