簡體   English   中英

如何確保通過Java 7通過SFTP上傳的所有文件都可以通過Java7使用?

[英]How to make sure all files uploaded via SFTP in watched directory are ok to use via Java7?

我正在使用WatchService監視目錄。 另一個第三方將通過SFTP將大型CSV文件上傳到該目錄。 我必須等到所有文件都完成后才能開始處理文件。

我現在的麻煩是,一旦上傳開始,SFTP就會創建文件,我得到ENTRY_CREATE並不斷獲得ENTRY_MODIFY直到文件完成。 無論如何,有沒有告訴文件是否真的完成了。

這是我使用的代碼,是我從Java文檔獲得的

public class WatchDir {

private final WatchService watcher;
private final Map<WatchKey, Path> keys;
private final boolean recursive;
private boolean trace = false;

@SuppressWarnings("unchecked")
static <T> WatchEvent<T> cast(WatchEvent<?> event) {
    return (WatchEvent<T>) event;
}

/**
 * Register the given directory with the WatchService
 */
private void register(Path dir) throws IOException {
    WatchKey key = dir.register(watcher, ENTRY_CREATE, ENTRY_DELETE, ENTRY_MODIFY);
    if (trace) {
        Path prev = keys.get(key);
        if (prev == null) {
            System.out.format("register: %s\n", dir);
        } else {
            if (!dir.equals(prev)) {
                System.out.format("update: %s -> %s\n", prev, dir);
            }
        }
    }
    keys.put(key, dir);
}

/**
 * Register the given directory, and all its sub-directories, with the
 * WatchService.
 */
private void registerAll(final Path start) throws IOException {
    // register directory and sub-directories
    Files.walkFileTree(start, new SimpleFileVisitor<Path>() {
        @Override
        public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs)
                throws IOException {
            register(dir);
            return FileVisitResult.CONTINUE;
        }
    });
}

/**
 * Creates a WatchService and registers the given directory
 */
WatchDir(Path dir, boolean recursive) throws IOException {
    this.watcher = FileSystems.getDefault().newWatchService();
    this.keys = new HashMap<WatchKey, Path>();
    this.recursive = recursive;

    if (recursive) {
        System.out.format("Scanning %s ...\n", dir);
        registerAll(dir);
        System.out.println("Done.");
    } else {
        register(dir);
    }

    // enable trace after initial registration
    this.trace = true;
}

/**
 * Process all events for keys queued to the watcher
 */
void processEvents() {
    for (; ; ) {

        // wait for key to be signalled
        WatchKey key;
        try {
            key = watcher.take();
        } catch (InterruptedException x) {
            return;
        }

        Path dir = keys.get(key);
        if (dir == null) {
            System.err.println("WatchKey not recognized!!");
            continue;
        }

        for (WatchEvent<?> event : key.pollEvents()) {
            WatchEvent.Kind kind = event.kind();

            // TBD - provide example of how OVERFLOW event is handled
            if (kind == OVERFLOW) {
                continue;
            }

            // Context for directory entry event is the file name of entry
            WatchEvent<Path> ev = cast(event);
            Path name = ev.context();
            Path child = dir.resolve(name);

            // print out event
            System.out.format("%s: %s\n", event.kind().name(), child);

            // if directory is created, and watching recursively, then
            // register it and its sub-directories
            if (recursive && (kind == ENTRY_CREATE)) {
                try {
                    if (Files.isDirectory(child, NOFOLLOW_LINKS)) {
                        registerAll(child);
                    }
                } catch (IOException x) {
                    // ignore to keep sample readbale
                }
            }
        }

        // reset key and remove from set if directory no longer accessible
        boolean valid = key.reset();
        if (!valid) {
            keys.remove(key);

            // all directories are inaccessible
            if (keys.isEmpty()) {
                break;
            }
        }
    }
}

static void usage() {
    System.err.println("usage: java WatchDir [-r] dir");
    System.exit(-1);
}

public static void main(String[] args) throws IOException {
    // parse arguments
    if (args.length == 0 || args.length > 2)
        usage();
    boolean recursive = false;
    int dirArg = 0;
    if (args[0].equals("-r")) {
        if (args.length < 2)
            usage();
        recursive = true;
        dirArg++;
    }

    // register directory and process its events
    Path dir = Paths.get(args[dirArg]);
    new WatchDir(dir, recursive).processEvents();
}

}

在Linux下,您可以使用“ inotify”工具。 它們可能會帶着所有主要的特性到達。 這是它的WikiWiki-Inotify

請注意,在受支持的事件列表中,您具有:

IN_CLOSE_WRITE-當打開的待寫文件關閉時發送

IN_CLOSE_NOWRITE-當打開的文件無法寫入時關閉時發送

這些是您要尋找的。 我沒有在Windows上看到類似的東西。 現在,關於使用它們,可以有多種方法。 我用了一個Java庫jnotify

請注意,該庫是跨平台的,因此您不想使用主類,因為Windows不支持關閉文件的事件。 您將需要使用linux API,它提供了完整的linux功能。 只需閱讀描述頁面,您就會知道它的要求: jnotify-Linux

請注意,在我的情況下,我必須下載庫源,因為我需要將共享對象文件“ libjnotify.so”編譯為64位。 提供的一種只能在32位以下使用。 也許他們現在提供您可以檢查。

檢查示例代碼,以及如何添加和刪除監視。 只需記住使用“ JNotify_linux”類而不是“ JNotify”,然后可以在操作中使用掩碼。

私有最終int MASK = JNotify_linux.IN_CLOSE_WRITE;

希望它對您有用。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM