How do I check whether a file is a directory, do the same for its sub directories and their contents recursively and copy them to another location

Viewed 30

I am new to programming and I have a problem. I need to check whether a file is a directory or not, if yes need to do the following :

  1. check whether it has contents. Contents can be sub-directories or just files.
  2. need to do the check recursively for every file inside the parent directory
  3. copy each directory and file to another location, preserving the directory structure.
  4. Also need to copy the database entries corresponding to every file/directory to another table
    along with the actual files
1 Answers

The process a java.io.File.isDirectory() alters the checking process whether a file with given a specified path name might be a directory or not.

Simply the code returns true if the file is specified by the path name is a directory and false in the opposite case.

import java.io.File;
public class Demo {
   public static void main(String[] args) {
      try {
         File file = new File("demo1.txt");
         file.createNewFile();
         System.out.println("Is directory? " + file.isDirectory());
      } catch(Exception e) {
         e.printStackTrace();
      }
   }
}

output: Is directory? false

let's see how the code is working: a small snippet that mimics the about the code is written down.

try {
   File file = new File("demo1.txt");
   file.createNewFile();
   System.out.println("Is directory? " + file.isDirectory());
} catch(Exception e) {
   e.printStackTrace();
}

Related