Mariam Elbarbary

Without some goal and some effort to reach it, no one can live.

Simple Java Code to Copy folders/files from one directory to another — May 20, 2015

Simple Java Code to Copy folders/files from one directory to another

This is a simple Java class  that  open the source Folder and read the content of the folder

If it contains folders or files with  ‘offline’ in its name  move it to the offline folder and if it contains ‘online’ move it to the Online folder.

if you have any questions don’t hesitate to ask.

/* Mariam Elbarbary */
import java.io.*;
import java.nio.file.Files;
import java.util.*;
import javax.swing.*;

public class Main {

public static void copyDirectory(File sourceLocation, File targetLocation) throws IOException
{
if (sourceLocation.isDirectory()) {
if (!targetLocation.exists()) {
targetLocation.mkdir();
}
String[] children = sourceLocation.list();
for (int i=0; i<children.length; i++) {
copyDirectory(new File(sourceLocation, children[i]), new File(targetLocation, children[i]));
}
} else {
InputStream in = new FileInputStream(sourceLocation);
OutputStream out = new FileOutputStream(targetLocation); // Copy the bits from instream to outstream byte[] buf = new byte[1024]; int len; try { while ((len = in.read(buf)) > 0) {
out.write(buf, 0, len);
//}
} catch (IOException e) {
e.printStackTrace();
}
in.close();
out.close();
//}
}
public static void main(String[] args) throws IOException {
String DirectorySource = “C:\\workset\\CopySource”;
File source = new File(DirectorySource);
if(!source.exists()){
System.out.println(“Directory does not exist.”);
}
String dest2 = “C:\\workset\\Offline”;
String dest1 = “C:\\workset\\Online”;
File destination1 = new File(dest1);
File destination2 = new File(dest2);
// If folder doesn’t exist create a new folder
if(!destination1.exists()){
destination1.mkdir();
}
if(!destination2.exists()){
destination2.mkdir();
}
/***
Open Source DIrectory and read the name of the folders
If it contains Offline move it to the offline folder and if it contains Online move it to the Online folder
***/
// source.renameTo(destination);
//list all the directory contents
String files[] = source.list();
for (String file : files) {
//construct the src and dest file structure
File srcFile = new File(source, file);
File destFile = new File(file);
if(file.contains(“Offline”)){
destFile = new File(destination2, file);
}else if (file.contains(“Online”)) {
destFile = new File(destination1, file);
}
copyDirectory(srcFile, destFile);
}
}
}