DefaultFileProcessor implements FileProcessor { public long copy( File source, File target, ProgressListener listener ) throws IOException { long total = 0; FileInputStream fis = null; OutputStream fos = null; try { fis = new FileInputStream( source ); mkdirs( target.getParentFile() ); fos = new BufferedOutputStream( new FileOutputStream( target ) ); ByteBuffer buffer = ByteBuffer.allocate( 1024 * 32 ); byte[] array = buffer.array(); while ( true ) { int bytes = fis.read( array ); if ( bytes < 0 ) { break; } fos.write( array, 0, bytes ); total += bytes; if ( listener != null && bytes > 0 ) { try { buffer.rewind(); buffer.limit( bytes ); listener.progressed( buffer ); } catch ( Exception e ) { } } } } finally { close( fis ); close( fos ); } return total; }  boolean mkdirs( File directory ); void write( File file, String data ); long copy( File source, File target, ProgressListener listener ); void move( File source, File target );  }
@Test public void testCopy() throws IOException { File file = TestFileUtils.createTempFile( "testCopy\nasdf" ); File target = new File( targetDir, "testCopy.txt" ); fileProcessor.copy( file, target, null ); TestFileUtils.assertContent( "testCopy\nasdf".getBytes( "UTF-8" ), file ); file.delete(); }
@Test public void testOverwrite() throws IOException { File file = TestFileUtils.createTempFile( "testCopy\nasdf" ); for ( int i = 0; i < 5; i++ ) { File target = new File( targetDir, "testCopy.txt" ); fileProcessor.copy( file, target, null ); TestFileUtils.assertContent( "testCopy\nasdf".getBytes( "UTF-8" ), file ); } file.delete(); }
@Test public void testCopyEmptyFile() throws IOException { File file = TestFileUtils.createTempFile( "" ); File target = new File( targetDir, "testCopyEmptyFile" ); target.delete(); fileProcessor.copy( file, target, null ); assertTrue( "empty file was not copied", target.exists() && target.length() == 0 ); target.delete(); }
@Test public void testProgressingChannel() throws IOException { File file = TestFileUtils.createTempFile( "test" ); File target = new File( targetDir, "testProgressingChannel" ); target.delete(); final AtomicInteger progressed = new AtomicInteger(); ProgressListener listener = new ProgressListener() { public void progressed( ByteBuffer buffer ) throws IOException { progressed.addAndGet( buffer.remaining() ); } }; fileProcessor.copy( file, target, listener ); assertTrue( "file was not created", target.isFile() ); assertEquals( "file was not fully copied", 4, target.length() ); assertEquals( "listener not called", 4, progressed.intValue() ); target.delete(); }