NIO(3) FileChannel

来源:互联网 发布:powershell for linux 编辑:程序博客网 时间:2024/06/07 09:58

      Java NIO中的FileChannel是一个连接到文件的通道。可以通过文件通道读写文件。FileChannel无法设置为非阻塞模式,它总是运行在阻塞模式下。

  • 打开FileChannel
    在使用FileChannel之前,必须先打开它。但是,我们无法直接打开一个FileChannel,需要通过使用一个InputStream、OutputStream或RandomAccessFile来获取一个FileChannel实例(这里通过InputStream和OutputStream讲解,前面已经使用了RandomAccessFile)
@Test@SuppressWarnings("resource")public void fileChannel() {    try {        // 通过文件输入流获取文件通道对象        FileChannel inChannel = new FileInputStream(                new File("D:/360Downloads/task.ini")).getChannel();        // 通过文件输出流获取追加文件通道对象        FileChannel outChannel = new FileOutputStream(                new File("D:/360Downloads/task.ini"), true).getChannel();        // 获取缓冲区        ByteBuffer buf = ByteBuffer.allocate(128);        buf.clear();        // 读取数据        int len = inChannel.read(buf);        System.out.println(new String(buf.array(), 0, len));        // 追写写数据        ByteBuffer buf2 = ByteBuffer                .wrap("Hello jack! Nice to meet to you ! \n".getBytes());        outChannel.write(buf2);        // 调用position(long pos)方法设置FileChannel当前开始读写的位置。        System.out.println("------------------------------------");        buf.clear();        inChannel.position(30);        int hasRead = inChannel.read(buf);        while (-1 != hasRead) {            buf.flip();            // 是否已经达到限制:当前读的位置是否已经 > inChannel.size()            while (buf.hasRemaining()) {                System.out.print((char) buf.get());            }            buf.clear();            hasRead = inChannel.read(buf);        }        // 释放资源        inChannel.close();        outChannel.close();    } catch (Exception e) {        e.printStackTrace();    }}

FileChannel的truncate方法
      可以使用FileChannel.truncate()方法截取一个文件。截取文件时,文件将中指定长度后面的部分将被删除。如:

channel.truncate(1024);

FileChannel的force方法
      FileChannel.force(true);方法将通道里尚未写入磁盘的数据强制写到磁盘上。

0 0