使用FileChannel读取文件

Once you call read( ) to tell the FileChannel to store bytes into the ByteBuffer, you must call flip( ) on the buffer to tell it to get ready to have its bytes extracted (yes, this seems a bit crude, but remember that it’s very low-level and is done for maximum speed). And if we were to use the buffer for further read( ) operations, we’d also have to call clear( ) to prepare it for each read( ). You can see this in a simple file copying program:

// : c12:ChannelCopy.java
//  Copying a file using channels and buffers
//  {Args: ChannelCopy.java test.txt}
//  {Clean: test.txt} 
import  java.io. * ;
import  java.nio. * ;
import  java.nio.channels. * ;

public   class  ChannelCopy {
    
private   static   final   int  BSIZE  =   1024 ;

    
public   static   void  main(String[] args)  throws  Exception {
        
if  (args.length  !=   2 ) {
            System.out.println(
" arguments: sourcefile destfile " );
            System.exit(
1 );
        }
        FileChannel in 
=   new  FileInputStream(args[ 0 ]).getChannel(), out  =   new  FileOutputStream(
                args[
1 ]).getChannel();
        ByteBuffer buffer 
=  ByteBuffer.allocate(BSIZE);
        
while  (in.read(buffer)  !=   - 1 ) {
            buffer.flip(); 
//  Prepare for writing
            out.write(buffer);
            buffer.clear(); 
//  Prepare for reading
        }
    }
//  /:~

你可能感兴趣的:(exception,String,Class,buffer,import,each)