NioDemo.java

Download NioDemo.java

 1: // Demo of using the java.nio package.
 2: // This application copies a file, efficiently.
 3: // (Note the buffer size chosen;  If you know your operating
 4: // system's block (or "cluster") size, using that will be the
 5: // most efficient.
 6: //
 7: // Written 1/2009 by Wayne Pollock, Tampa Florida USA
 8: 
 9: import java.io.*;
10: import java.nio.*;
11: import java.nio.channels.*;
12: 
13: public class NioDemo
14: {
15:    private static final int BUF_SIZE = 4096;
16:    public static void main ( String [] args ) throws Exception
17:    {
18:       if ( args.length != 2 )
19:       {  System.err.println( "Usage: NioDemo inputFile outputFile" );
20:          return;
21:       }
22: 
23:       FileInputStream fin = new FileInputStream( args[0] );
24:       FileChannel cin = fin.getChannel();
25:       FileOutputStream fout = new FileOutputStream( args[1] );
26:       FileChannel cout = fout.getChannel();
27: 
28:       ByteBuffer buf = ByteBuffer.allocate( BUF_SIZE );
29: 
30:       System.out.print( "Copying \"" + args[0] + "\" to \""
31:          + args[1] + "\":." );
32: 
33:       buf.clear();
34:       while ( cin.read(buf) != -1 ) {
35:          System.out.print( "." );
36:          buf.flip();
37:          cout.write(buf);
38:          buf.clear();
39:       }
40: 
41:       System.out.println( "Done!" );
42: 
43:       fin.close(); fout.close();
44:    }
45: }