Teachnique
      CourseRoadmaps
      Login

      OverviewHistoryFeaturesJava 8 - New Featuresvs C++Virtual Machine(JVM)JDK vs JRE vs JVMHello World ProgramEnvironment SetupBasic SyntaxVariable TypesData TypesType CastingUnicode SystemBasic OperatorsCommentsStreamsNew Date-Time API

      Loop ControlDecision Makingif-else Statementswitch statementfor loopfor each Loopwhile Loopdo...while Loopbreak Statementcontinue Statement

      OOPs (Object-Oriented Programming) ConceptsObject and ClassesClass AttributesClass MethodsMethodsVariable ScopesConstructorsAccess ModifiersInheritanceAggregationPolymorphismOverridingMethod OverloadingDynamic BindingStatic BindingInstance Initializer BlockAbstractionEncapsulationInterfacesPackagesInner classesStatic ClassesAnonymous ClassesSingleton ClassWrapper ClassesEnum Class

      Number ClassBoolean classCharacter ClassArraysMath Class

      File ClassCreating FilesWrite To FilesReading FileDelete FilesDirectory OperationsFiles and I/O

      ExceptionsTry Catch BlockTry with ResourcesMultiple Catch BlocksNested Try BlockFinally BlockThrows and Throw | Throw an ExceptionException PropagationBuilt-in ExceptionsCustom Exception

      MultithreadingThread Life CycleCreating a ThreadStarting a ThreadJoining ThreadsNaming a Thread with ExamplesScheduling Threads with ExamplesThread PoolsMain ThreadThread PriorityDaemon ThreadThreadGroup ClassJVM Shutdown Hook

      Thread SynchronizationBlock SynchronizationStatic SynchronizationInter Thread CommunicationThread DeadlockInterrupting ThreadThread ControlReentrant Monitor

      NetworkingSocket ProgrammingURL ProcessingURL ClassURLConnection ClassHttpURLConnection ClassSocket Class with ExamplesGenerics

      Collections FrameworkCollection Interface

      List InterfaceArrayList Class

      Queue InterfaceArrayDeque Class

      Map InterfaceSortedMap Interface

      Set InterfaceSortedSet Interface

      Data Structures Enumeration Interface BitSet Class

      How to Use Iterator?How to Use Comparator?How to Use Comparable?

      RecursionRegular ExpressionsSerializationString ClassJava Arrays - Class

      Feedback

      Submit request if you have any questions.

      Course
      Delete Files

      Java Tutorial

      This Java tutorial is tailored for newcomers, offering a journey from basic principles to complex Java programming techniques. Completing this tutorial equips you with a solid understanding of Java, preparing you for advanced learning. You'll emerge ready to tackle the challenges of becoming a top-tier software engineer, with the skills to innovate and excel in the vast world of software development.

      Deleting Files

      Deleting Files in Java

      To delete a file in Java, you can use the File.delete() method. This method deletes the files or directory from the given path.

      Syntax

      Following is the syntax of deleting a file using File.delete() method
      File file = new File("C:/java/hello.txt");
      
      if(file.exists()){
      file.delete();
      }

      Deleting File from Current Directory

      Following is the example to demonstrate File.delete() method usage to delete an existing file in current directory

      Example

      package com.tutorialspoint;
      
      import java.io.BufferedWriter;
      import java.io.File;
      import java.io.FileWriter;
      import java.io.IOException;
      
      public class FileTest {
      public static void main(String args[]) throws IOException {
      BufferedWriter out = new BufferedWriter (new FileWriter("test.txt"));
      out.write("test data");
      out.close();
      
      File file = new File("test.txt");
      if(file.exists()) {
      boolean success = file.delete();
      
      if (success) {
      System.out.println("The file has been successfully deleted.");
      }else {
      System.out.println("The file deletion failed.");
      }
      }else {
      System.out.println("The file is not present.");
      }
      }
      }

      Output

      The above code would create file test.txt and would write given numbers in binary format. Same would be the output on the stdout screen.
      This will produce the following result
      The file has been successfully deleted.

      Deleting File That Does Not Exist

      Following is the example to demonstrate File.delete() method call to delete an non-existing file in current directory. As file is not present, it returns false as result.

      Example

      package com.tutorialspoint;
      
      import java.io.File;
      import java.io.IOException;
      
      public class FileTest {
      public static void main(String args[]) throws IOException {
      File file = new File("test1.txt");
      boolean success = file.delete();
      
      if (success) {
      System.out.println("The file has been successfully deleted.");
      }else {
      System.out.println("The file deletion failed.");
      }
      }
      }

      Output

      The above code would create file test.txt and would write given numbers in binary format. Same would be the output on the stdout screen.
      This will produce the following result
      The file deletion failed.

      Deleting All Files From Given Directory

      Following is the example to demonstrate File.delete() method usage to delete all files in given directory recursively.

      Example

      package com.tutorialspoint;
      
      import java.io.File;
      import java.io.IOException;
      
      public class FileTest {
      public static void deleteFiles(File dirPath) {
      File filesList[] = dirPath.listFiles();
      for(File file : filesList) {
      if(file.isFile()) {
      file.delete();
      } else {
      deleteFiles(file);
      }
      }
      }
      public static void main(String args[]) throws IOException {
      //Creating a File object for directory
      File file = new File("D:\\test");
      //List of all files and directories
      deleteFiles(file);
      System.out.println("Files deleted.");
      }
      }

      Output

      The above code would create file test.txt and would write given numbers in binary format. Same would be the output on the stdout screen.
      This will produce the following result
      Files deleted.