package test1;
    import java.io.IOException;
    import java.io.RandomAccessFile;
    import java.nio.*;
    import java.nio.channels.FileChannel;
    public class Test2NIO {
    public static void main(String[] args) {
    // NIO

    RandomAccessFile aFile = null;
    try{
    aFile = new RandomAccessFile(“C:/users/yctongd/Desktop/fortest.txt”,”rw”);
    FileChannel fileChannel = aFile.getChannel();
    ByteBuffer buf = ByteBuffer.allocate(1024);
    int bytesRead = fileChannel.read(buf);
    System.out.println(“共” + bytesRead + “字节”);
    while(bytesRead != -1){
    buf.flip();
    while(buf.hasRemaining()){
    System.out.print((char)buf.get());
    }
    buf.compact();
    bytesRead = fileChannel.read(buf);
    }
    }catch(IOException e){
    e.printStackTrace();
    }finally{
    try{
    if(aFile != null){
    aFile.close();
    }
    }catch(IOException e){
    e.printStackTrace();
    }
    }
    }
    }