Skip to content

Instantly share code, notes, and snippets.

@swapi
Forked from anonymous/sync.py
Created December 20, 2012 13:01
Show Gist options
  • Save swapi/4345197 to your computer and use it in GitHub Desktop.
Save swapi/4345197 to your computer and use it in GitHub Desktop.
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