Avoid detecting incomplete files when watching a directory for changes in java

前端 未结 5 786
庸人自扰
庸人自扰 2020-12-31 11:34

I am watching a directory for incoming files (using FileAlterationObserver from apache commons).

class Example implements FileAlterationListener {
    public         


        
5条回答
  •  醉话见心
    2020-12-31 11:48

    If you use FileAlterationListener and add a FileAlterationListenerAdaptor you can implement the methods you need and monitor the files with a FileAlterationMonitor ...

    public static void main( String[] args ) throws Exception {
    
        FileAlterationObserver fao = new FileAlterationObserver( dir );
        final long interval = 500;
        FileAlterationMonitor monitor = new FileAlterationMonitor( interval );
        FileAlterationListener listener = new FileAlterationListenerAdaptor() {
    
            @Override
            public void onFileCreate( File file ) {
                try {
                    System.out.println( "File created: " + file.getCanonicalPath() );
                } catch( IOException e ) {
                    e.printStackTrace( System.err );
                }
            }
    
            @Override
            public void onFileDelete( File file ) {
                try {
                    System.out.println( "File removed: " + file.getCanonicalPath() );
                } catch( IOException e ) {
                    e.printStackTrace( System.err );
                }
            }
    
            @Override
            public void onFileChange( File file ) {
                try {
                    System.out.println( file.getName() + " changed: ");
                } catch( Exception e ) {
                    e.printStackTrace();
                } 
            }
        };
        // Add listeners...
        fao.addListener( listener );
        monitor.addObserver( fao );
        monitor.start();
    }
    

提交回复
热议问题