views:

168

answers:

6

Is there a library to take a folder, take a snapshot of its content, do some modifications and then restore it to its previous state from directly from a java program (i.e. not from the command line) ?

Edit: Basically, i am working on a very large folder: 80mb, ~7000 files. And I want to restore only files that were modified as fast as possible. Only copying everything back looks time consuming.

+2  A: 

I don't know of a non-standard library for what you want, but you could try copying the contents of the directory into a temporary directory and the copy it back when you are done (and delete the temporary directory).

Take a look at java.io.File

And here is another library specifically for copying files/folders.

To your edit: you'll have to find some way to keep track of or "flag" files that were modified. Maybe extend the file class with such a "flag" property? You could keep all the files in memory, but then you'd have to worry about running out of memory if these directories ever get too large.

Bryan Denny
A: 

Yeah! There is enough API functionality to do this!

Do you want to take a recursive snapshot?

I like the groovy syntax a lot:

currentDir.eachFileRecurse{ file ->
...}
Martin K.
A: 

Not exactly Java, but gives less headache ...

public void before(String origDir, String tmpDir) {
    try {
      Runtime.getRuntime().exec("cp -pr " + origDir + " " + tmpDir).waitFor();
    } catch (IOException err) {
      ...
    }
}


public void after(String origDir, String tmpDir) {
    try {
      String rndDir = createRandomName();
      Runtime.getRuntime().exec("mv " + origDir + " " + rndDir).waitFor();
      Runtime.getRuntime().exec("mv " + tmpDir + " " + origDir).waitFor();
      Runtime.getRuntime().exec("rm " + rndDir);
    } catch (IOException err) {
      ...
    }
}
Zed
A: 

I would take a look at the apache-commons IO library. I've notably used the DirectoryWalker which is really convenient to recursively inspect the content of a Directory.

LB
+2  A: 

The snapshot is basically a recursive copy through all directories, and that seems unavoidable. In terms of restoring, just delete the directory and rename the temporary directory with the original name.

If this is for functional testing, how about having a known good directory and copying it at the beginning of the test? That way there is no snapshot taking. That only works, of course, if you always start with a known set of files.

As for the actual recursive copy, Apache has a method for that in Commons-IO, as well as one to do a recursive delete.

Yishai
A: 

Watching the directory (and subdirectories) for changes, accumulating them and then when you want to reverse the changes, only copy the changed files.

See for example:

http://twit88.com/blog/2007/10/02/develop-a-java-file-watcher/

http://www2.hawaii.edu/~qzhang/FileSystemWatcher/index.html

elhoim