import java.io.*; import javax.swing.*; public class MovingFile{ public static void main(String[] args) throws IOException{ int a = 0; BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); System.out.print("Enter the file or directory name that has to be moved : "); String src = in.readLine(); if(src.equals("")){ System.out.println("Invalid directory or file name."); System.exit(0); } File source = new File(src); if(!source.exists()){ System.out.println("File or directory does not exist."); System.exit(0); } System.out.print("Enter the complete path where file or directory has to moved: "); String dest = in.readLine(); if(dest.equals("")){ System.out.println("Invalid directory or file name."); System.exit(0); } File destination = new File(dest); if(!destination.exists()){ System.out.print("Mentioned directory does not exist.\nDo you want to create a new directory(Y/N)? "); String chk = in.readLine(); if(chk.equals("Y") || chk.equals("y")){ destination.mkdir(); copyDirectory(source, destination); a = 1; } else if(chk.equals("N") || chk.equals("n")){ System.exit(0); } else{ System.out.println("Invalid Entry!"); System.exit(0); } } else{ int num = JOptionPane.showConfirmDialog(null,"Given file or folder name already exists.\nDo you want to replace now?"); if(num == 0){ copyDirectory(source, destination); a = 1; } } if(a == 1){ System.out.println("File or directory moved successfully."); if(!delete(source)){ throw new IOException("Unable to delete original folder"); } } else if(a == 0){ System.exit(0); } } public static void copyDirectory(File sourceDir, File destDir) throws IOException{ if(!destDir.exists()){ destDir.mkdir(); } File[] children = sourceDir.listFiles(); for(File sourceChild : children){ String name = sourceChild.getName(); File destChild = new File(destDir, name); if(sourceChild.isDirectory()){ copyDirectory(sourceChild, destChild); } else{ copyFile(sourceChild, destChild); } } } public static void copyFile(File source, File dest) throws IOException{ if(!dest.exists()){ dest.createNewFile(); } InputStream in = null; OutputStream out = null; try{ in = new FileInputStream(source); out = new FileOutputStream(dest); byte[] buf = new byte[1024]; int len; while((len = in.read(buf)) > 0){ out.write(buf, 0, len); } } finally{ in.close(); out.close(); } } public static boolean delete(File resource) throws IOException{ if(resource.isDirectory()){ File[] childFiles = resource.listFiles(); for(File child : childFiles){ delete(child); } } return resource.delete(); } }