天天看點

粗人之玩轉Channel

文章目錄

        • 1、檔案讀取
        • 2、檔案寫入

1、檔案讀取

public static public void main( String args[] ) throws Exception {  
    FileInputStream fin = new FileInputStream("E://test.txt");

    // 擷取通道  
    FileChannel fc = fin.getChannel();  

    // 建立緩沖區  
    ByteBuffer buffer = ByteBuffer.allocate(1024);  

    // 讀取資料到緩沖區  
    fc.read(buffer);  

    buffer.flip();  

    while (buffer.remaining() > 0) {  
        byte b = buffer.get();  
        System.out.print(((char)b));  
    }  

    fin.close();
}  
           

2、檔案寫入

public static private final byte message[] = { 83, 111, 109, 101, 32, 98, 121, 116, 101, 115, 46 };

public static public void main( String args[] ) throws Exception {  
    FileOutputStream fout = new FileOutputStream( "E://test.txt" );

    FileChannel fc = fout.getChannel();  

    ByteBuffer buffer = ByteBuffer.allocate( 1024 );  

    for (int i=0; i<message.length; ++i) {  
        buffer.put( message[i] );  
    }  

    buffer.flip();   

    fc.write( buffer );  

    fout.close();  
}  
           

繼續閱讀