Created
December 20, 2012 13:01
-
-
Save anonymous/4345195 to your computer and use it in GitHub Desktop.
Keeps the files in two folder in sync. Uses java 7 features.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from java.io import File | |
from java.nio.file import Files | |
from java.nio.file import FileSystems | |
from java.nio.file.StandardWatchEventKinds import * | |
from java.nio.file.StandardCopyOption import * | |
from java.nio.file import Paths | |
source = '/source/file/path' | |
target = '/dest/file/path' | |
sourcef = File(source) | |
def copy(src, dest): | |
counter = 1 | |
while dest.toFile().exists(): | |
dest = dest.getParent().resolve( | |
src.getFileName().toString() + ("-%d" % counter)); | |
counter += 1 | |
Files.copy(src, dest, []) | |
def copyFiles(): | |
for f in sourcef.list(): | |
src = Paths.get(source, [f]) | |
dest = Paths.get(target, [f]) | |
copy(src, dest) | |
watchService = FileSystems.getDefault().newWatchService() | |
ckey = Paths.get(source, []).register(watchService, [ENTRY_CREATE, ENTRY_DELETE, ENTRY_MODIFY]) | |
copyFiles() | |
while 1: | |
key = watchService.take() | |
for event in key.pollEvents(): | |
if event.kind() == ENTRY_CREATE: | |
print 'File created = ', event.context(), '; copying it...' | |
src = Paths.get(source, [event.context().toString()]) | |
dest = Paths.get(target, [event.context().toString()]) | |
copy(src, dest) | |
elif event.kind() == ENTRY_MODIFY: | |
print 'File modified = ', event.context(), '; copying it...' | |
src = Paths.get(source, [event.context().toString()]) | |
dest = Paths.get(target, [event.context().toString()]) | |
Files.copy(src, dest, [REPLACE_EXISTING]) | |
if not key.reset(): | |
break |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment