I back up my data to an external drive quite often and have to sift through files I have and haven’t already transferred over. I thought it would be useful to create a tool that will allow me to select two directories, compare them, and then transfer the files over with a few clicks of a button.
I’m sure projects of this sort already exist out there, so for me, it is mainly a learning experience.
So to start it off, I have a method that will get all my folders and files so that I can populate my tree:
public static void listAllFiles(String directory, DefaultMutableTreeNode parent, Boolean recursive) {
File [] children = new File(directory).listFiles();
for (int i = 0; i < children.length; i++) {
DefaultMutableTreeNode node = new DefaultMutableTreeNode(children[i].getName());
if (children[i].isDirectory() && recursive) {
parent.add(node);
listAllFiles(children[i].getPath(), node, recursive);
} else if (!children[i].isDirectory()){
parent.add(node);
}
}
}
Once the method is called, I simply create my JTree and add it to my view:
myTree = new JTree(parent);
jScrollPane1.setViewportView(myTree);
So once I have my two JTrees, how would I compare the nodes to see what files don’t exist on my external? Would it be easier to just compare the array of files?
Edit
By efficient, I mean is least likely to bog down the computer in case the file tree consists of thousands of files.
I think the answer is: Why compare JTree’s? JTree is a GUI element for displaying data – not a data structure for storing/comparing/manipulating data.
So what you should do is come up with a data structure to compare your data in, and then use the JTree to display the results of your compare. Assuming CPU resources are what you want to conserve, I’d say you want to use a TreeMap.
Essentially you’d build your
TreeMapon the source file system, and then remove items from theTreeMapas you find (and match) them on the destination file system. Once you’re done with the compare, you can display files that still need syncing in aJTree.Best of all, since TreeMap guarentees log(n) for the
containsKey,get,putandremovemethods, it’ll cost you nLog(n) to insert all the files in the source, and nLog(n) to remove (basically your compare) all the keys in the destination.Edit
Oh, and WinMerge is one of the best tools I’ve ever used for file system comparisons. Of course, I’ve never used it for syncing a backup drive…