Streaming files and moving them after read

后端 未结 4 541
心在旅途
心在旅途 2021-02-02 12:24

I want to stream the lines contained in files but MOVING each file to another folder once it has been processed.

The current process is like this:

Explanation:

4条回答
  •  佛祖请我去吃肉
    2021-02-02 13:04

    Can do something like this:

        files
            .map( file -> {
                getBufferedReader( file ).lines()
                    .forEach( System.out::println );
                return file;
            } )
            .forEach( this::moveFile );
    

    Update for checked exceptions and Reader.close:

    Admittedly, this doesn't run close() in a finally block, so that is a downside. The point of this update is mainly to illustrate a way of dealing with checked exceptions in Java 8 streams.

    Let's say you have the following utility code available:

    private interface ThrowingFunction
    {
        O apply( I input ) throws Exception;
    }
    
    private  Function unchecked( ThrowingFunction checked )
    {
        return i -> {
            try {
                return checked.apply( i );
            }
            catch ( Exception e ) {
                throw new RuntimeException();
            }
        };
    }
    
    private interface ThrowingConsumer
    {
        void consume( T input ) throws Exception;
    }
    
    private  Consumer unchecked( ThrowingConsumer checked )
    {
        return t -> {
            try {
                checked.consume( t );
            }
            catch ( Exception e ) {
                throw new RuntimeException();
            }
        };
    }
    
    private BufferedReader getBufferedReader( File file ) throws FileNotFoundException
    {
        return new BufferedReader( new InputStreamReader( new FileInputStream( file )));
    }
    

    Writing the actual code then becomes:

        files
            .map( file -> {
                Stream.of( file )
                    .map( unchecked( this::getBufferedReader ))
                    .map( reader -> {
                        reader.lines().forEach( System.out::println );
                        return reader;
                    } )
                    .forEach( unchecked( Reader::close ));
                return file;
            } )
            .forEach( this::moveFile );
    

提交回复
热议问题