在Java NIO包中FileChannel是用于读取、写入、映射和操作文件的通道。
下面通过利用FileChannel来进行文件的读写例子
1从txt文件中读取数据并且输出到控制台
public static void main(String[] args) throws IOException { /*需要通过 FileInputStream、FileOutputStream 或 RandomAccessFile对象来获取FileChannel * */ FileInputStream f1 = new FileInputStream("b.txt"); FileChannel fc1 = f1.getChannel(); ByteBuffer b1 = ByteBuffer.allocate(25);//初始化缓冲区大小 fc1.read(b1);//将文件通道里面的字节读到缓冲区中 b1.flip();//此方法将position置为0,limit放到position位置 while(b1.hasRemaining()) {// position<limit时返回true System.out.println((char)b1.get()); } fc1.close();//关闭通道 }此例子有两点细节:
第一 在使用fc1.read(b1)后此时缓冲区内的position(当前读取位置)和limit(读写上限的位置)是一样的,可以调用ByteBuffer的position()方法和limit()方法进行比较
第二 使用b1.flip()是为了将position置为0,limit放到position位置,在jdk源码中flip方法有:
public final Buffer flip() { limit = position; position = 0; mark = -1; return this; }所以接下来用while循环将缓冲区里面的字节转换成字符输出,hasRemaining源码如下:
public final boolean hasRemaining() { return position < limit; }2将字符串写入txt文件:
public static void main(String[] args) throws IOException { FileOutputStream f1 = new FileOutputStream("cd.txt"); FileChannel fc1 = f1.getChannel(); ByteBuffer buffer = ByteBuffer.wrap(new String("OPP555P").getBytes()); fc1.write(buffer); fc1.close();//关闭通道 }
