Here in this tutorial I will explain how to copy files or folders by reading them in a hierarchical way.

Program Flow : 

  1. Read Input File or Directory  path and Destination path
  2. Is input File is Directory or real File ?
  3. If it is directory, then create destination directory and list all files and send them to 2nd step
  4. If it is file, then create destination file and copy

Java Code :

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

public class CopyFiles {
   public static void main(String args[]) throws IOException {
       String source="D:\\Gate", destination = "D:\\Gate1";
       File file = new File(source);
       copyFiles(file, destination);     
   }
   
   public static void copyFiles(File file, String path) throws IOException {
          if(file.isDirectory()) {
              System.out.println("DIR "+ file.getAbsolutePath());
              File[] files = file.listFiles();
              String destDirPath = path + "\\" + file.getName();
              File destFile = new File(destDirPath);
              if(!destFile.exists()) {
                  destFile.mkdirs();
              }
              for(int i=0; i<files.length; i++) {
                  copyFiles(files[i],destDirPath);
              }
          } else {
              String destFilePath = path + "\\" + file.getName();
              File destFile = new File(destFilePath);
              if(!destFile.exists()) {
                  destFile.createNewFile();
              }
              System.out.println("File "+ file.getAbsolutePath());
              copyFileUsingStream(file, destFile);
          }
      }
   
   private static void copyFileUsingStream(File source, File dest) throws IOException {
        InputStream is = null;
        OutputStream os = null;
        try {
            is = new FileInputStream(source);
            os = new FileOutputStream(dest);
            byte[] buffer = new byte[1024];
            int length;
            while ((length = is.read(buffer)) > 0) {
                os.write(buffer, 0, length);
            }
        } finally {
            is.close();
            os.close();
        }
    }

}

0 comments:

Blogroll

Popular Posts