⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 directorypoller.java

📁 一个简易的轮训小程序 哈哈哈哈哈哈后 嘿嘿嘿嘿黑诶
💻 JAVA
📖 第 1 页 / 共 4 页
字号:
                try {
                    sleeping=true;
                    sleep(pollInterval);
                    sleeping=false;
                    if (verbose) {
                        System.out.println("Poller waking up");
                    }
                } catch(InterruptedException e) {
                    //System.out.println("Sleep interrupted");
                }
        } while(! shutdownRequested);
        if (verbose) System.out.println("Poller terminated.");
    }

    private void runCycle() {

    	// Notify wakeup
        if (!shutdownRequested)
            notify(new CycleStartEvent(this));

        // Initiate directories lookup. currentDir is a member
        // used also by the TimeFilenameFilter
        if (!shutdownRequested)
            for(currentDir=0;currentDir<dirs.length;currentDir++) {
                File dir = PathNormalizer.normalize(dirs[currentDir]);
                File originalDir = dir;

                // Notify directory lookup start
                notify(new DirectoryLookupStartEvent(this, dir));
                if (shutdownRequested) return;

                long filesLookupTime=System.currentTimeMillis();
                // Get the files
                File [] fls = dir.listFiles(filter);
                if (fls==null) {
                    System.err.println("Warning: directory "+dir+" does not exist");
                    fls=new File[0];
                }
                
                // Sort if required
                if (filesSortComparator!=null) {
                    if (verbose)
                        System.out.println("Sorting files by  "+filesSortComparator);
                    Arrays.sort(fls, filesSortComparator);
                }
                
                // Extract names (this could be factored out if it affects perfomance, my original code
                // was using just the file names)
                String [] files = new String[fls.length];
                for(int i=0;i<files.length;i++) files[i]=fls[i].getName();

                // If autoMove, then move the files in their destination
                // directory
                String [] movedFiles=new String[files.length]; // Only for autoMove mode
                int failedToMoveCount=0;
                if (autoMove) {
                    File autoMoveDir = getAutoMoveDirectory(dir);
                    for(int j=0;j<files.length;j++) {
                        File orig = new File(dir, files[j]);
                        File dest = new File(autoMoveDir, files[j]);

                        if (dest.exists()) {
                            // Delete the existing file. Notify if failed.
                            if (verbose)
                                System.out.println("[Automove] Attempting to delete existing "+dest.getAbsolutePath());
                            if (! dest.delete()) {
                                notify(new ExceptionSignal(new AutomoveDeleteException(orig, dest, "Could not delete "+dest.getAbsolutePath()), this));
                                failedToMoveCount++;
                                continue;
                            } else
                                if (verbose)
                                    System.out.println("[Automove] Deleted "+dest.getAbsolutePath());
                        }

                        // Move the file - notify the listeners if an exception occurs
                        if (verbose)
                                System.out.println("[Automove] Moving "+orig.getAbsolutePath()+" to "+autoMoveDir.getAbsolutePath()+File.separator);

                        autoMoveDir.mkdirs();
                        
                        try {
                            boolean proceed;
                            
                            // Check for locks if necessary
                            if (bypassLockedFiles) {
                                RandomAccessFile raf = new RandomAccessFile(orig, "rw"); 
                                FileChannel channel = raf.getChannel();
                                if (channel.tryLock()==null) { // File is locked
                                    if (verbose)
                                        System.out.println("[Automove] File "+orig.getAbsolutePath()+" is locked, ignoring");
                                    failedToMoveCount++;
                                    proceed=false;
                                } else {
                                    // A lock was acquired, so file transfer was complete: proceed.
                                    proceed=true;
                                }
                                channel.close(); // Unlock in either case
                            } else proceed=true;
                            
                            // "proceed" is true only if file was not locked, or lock check is disabled
                            if (proceed) {
                                if (! orig.renameTo(dest)) {
                                    notify(new ExceptionSignal(new AutomoveException(orig, dest, "Could not move "+orig.getName()+" to "+dest.getAbsolutePath()), this));
                                    failedToMoveCount++;
                                } else {
                                    //movedFiles[j]=autoMoveDir.getAbsolutePath()+File.separator+dest.getName();
                                    notify(new FileMovedEvent(this, orig, dest));
                                    movedFiles[j]=dest.getName();
                                    if (j+1==files.length) dir=autoMoveDir;
                                    if (verbose)
                                        System.out.println("[Automove] Moved "+orig.getAbsolutePath()+" to "+autoMoveDir.getAbsolutePath()+File.separator);
                                }
                            }
                            
                        } catch (FileNotFoundException e) {
                            notify(new ExceptionSignal(new AutomoveException(orig, dest, "Could not verify lock on "+orig.getName()), this));
                            failedToMoveCount++;
                        } catch (IOException e) {
                            notify(new ExceptionSignal(new AutomoveException(orig, dest, "Tentative lock attempt failed on "+orig.getName()), this));
                            failedToMoveCount++;
                        }
                        
                        
                        
                    }
                }

                // Notify the file set. (1.2.2b fix by Doug.Liao@fnf.com)
				if (autoMove) {
					// Shrink the array if needed, to avoid nulls due to files which
					// have failed to move
					String [] tmp = new String[files.length-failedToMoveCount];
					int c=0;
					for(int i=0;i<movedFiles.length;i++)
					if (movedFiles[i]!=null)
					tmp[c++]= movedFiles[i];
					files=tmp;
				}

				// dl: 6/19/03
				if (files.length > 0 ) {
				     notify(new FileSetFoundEvent(this, dir, files));
				} else {
					//System.out.println("No file found");
				}
                if (shutdownRequested) return;


                if (sendSingleFileEvent) {
                    // Notify each file
                    for(int j=0;j<files.length;j++) {
                        File file;

                        /*if (autoMove) file=new File(files[j]);
                        else */
                        file = new File(dir, files[j]);
                        // Notify file found
                        notify(new FileFoundEvent(this, file));
                        if (shutdownRequested) return;
                    }
                    if (shutdownRequested) return;


                }

                // Make sure that baseTime is set to the higher modified time
                // of the files being read

                if (isTimeBased()) {

                    if (verbose) System.out.println("Computing new base time");
                    // compute new base time, depending on the working mode
                    if (timeBasedOnLastLookup) {

                        baseTime[currentDir]=filesLookupTime; // Last lookup time
                    } else {

                        for (int j=0;j<files.length;j++) { // Highest file time
                            File file=new File(dir, files[j]);
                            long lastModifiedTime = file.lastModified();
                            if (lastModifiedTime > baseTime[currentDir]) {
                                baseTime[currentDir]=lastModifiedTime;
                            }
                        }
                        if (verbose)
                            System.out.println("Basetime for "+dirs[currentDir]+" is "+baseTime[currentDir]);
                    }

                }

                // Notify directory lookup end
                notify(new DirectoryLookupEndEvent(this, originalDir));
            }

        // Notify go to sleep
        if (! shutdownRequested)
            notify(new CycleEndEvent(this, baseTime));
    }

   	/**
	 * Get the current filter
	 */
	public FilenameFilter getFilter() {
		return filter;
	}

	/**
	 * Set the current filter. This can be invoked only when the
	 * poller is not running.
	 * @param filter the new filename filter to use.
	 */
	public void setFilter(FilenameFilter filter) {
		if (isAlive())
            throw new IllegalStateException("Can't call setFilter when the poller has already started");
		this.filter=filter;
	}
	
	/**
	 * Return the comparator to use to order file found events. Returns <b>null</b> if no comparator
	 * is set.
	 * 
	 * @return the comparator to use to order file found events. Returns <b>null</b> if no comparator
	 * is set. 
	 */
    public Comparator getFilesSortComparator() {
        return filesSortComparator;
    }
    
    /**
     * Set the comparator to use to order file found events. Use <b>null</b> to set no comparator.
     * <p>
     * The comparator receives File objects and decides on their respective order.
     * <p>
     * Two pre-packaged comparators {@link DirectoryPoller.ModificationTimeComparator} and
     * {@link DirectoryPoller.FileSizeComparator} are provided by this class. 
     * 
     * @param filesSortComparator
     */
    public void setFilesSortComparator(Comparator filesSortComparator) {
        this.filesSortComparator = filesSortComparator;
    }

    /**
     * Get the value of the BypassLockedFiles property. If the property is true, locked files will be 
     * ignored in automove mode. 
     * 
     * @return the value of the BypassLockedFiles property. 
     */
    public boolean isBypassLockedFiles() {
        return bypassLockedFiles;
    }

    /**
     * Set the value of the BypassLockedFiles property. If the property is true, locked files will be 
     * ignored in automove mode. 
     
     */
    public void setBypassLockedFiles(boolean supportSlowTransfer) {
        this.bypassLockedFiles = supportSlowTransfer;
    }

    public boolean isSleeping() {
        return sleeping;
    }

    /**
     * Turns on exception debugging. In case of exception signals are raised by the 
     * poller, they will be printed on standard output
     * @return true if exception debugging is active, false otherwise
     */
    public boolean isDebugExceptions() {
        return debugExceptions;
    }

    /**
     * Turns on exception debugging. In case of exception signals are raised by the 
     * poller, they will be printed on standard output
     * @param debugExceptions true to enable exception printing, false otherwise 
     */
    public void setDebugExceptions(boolean debugExceptions) {
        this.debugExceptions = debugExceptions;
    }

}

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -