Hi all,
I have to write a synchronization utility which synchronizes a target folder with a source folder:
i.e. I have the following source directory structure and would like to synchronize it.
C:\source\
|
+----Folder_A
| |
| +---Folder_A1
| | |
| | +---File_AA1.txt
| |
| +---FileA1.txt
|
+----Folder_B
| |
| +---Folder_B1
| | |
| | +---File_BB1.txt
| |
| +---File_B1.txt
|
+-----File_A.txt
When I run my program it will create the follwoing structure but it doesn't copy the files
D:\target\
|
+----Folder_A
| |
| +---Folder_A1
| |
| +---File_AA1
|
|
|
+----Folder_B
|
+---Folder_B1
|
+---File_BB1
My program is as follow:
public class Sync {
private static String strSource = "C:\\source";
private static String strTarget = "D:\\target";
public static void main( String[] args ) throws IOException {
Sync h = new Sync ();
h.doSync (strSource, strTarget);
}
public void doSync(String src, String trgt) throws IOException {
File source = new File (src);
File target = new File (trgt);
String Src = "";
String Trg = "";
File[] listFile = source.listFiles();
for (int i=0; i < listFile.length; i++) {
if (listFile[i].isDirectory()) {
if (!target.exists()) {
target.mkdir();
}
Src = listFile[i].getCanonicalPath();
Trg = target.getCanonicalPath() + "\\" + listFile[i].getName();
doSync(Src, Trg);
} else {
if (!target.exists()) {
FileInputStream from = new FileInputStream(listFile[i]);
target.createNewFile();
FileOutputStream to = new FileOutputStream(target.getName());
byte[] buffer = new byte[4096];
int bytesRead;
while ((bytesRead = from.read(buffer)) != -1) {
to.write(buffer, 0, bytesRead);
}
from.close();
to.close();
}
Src = listFile[i].getCanonicalPath();
Trg = target.getCanonicalPath();
}
}
}
}
Notice the out put folder structure: it doesn't create File_A1.txt, File_B1.txt and File_A.txt also notice the extention is missing.
The other files which are created, but it's not copied form the source directory, instead, it is just a file with that name, but not the content of the file.
Can someone please take a look and comment as where am I going wrong.
Thanks,