JAVA-6NIO之FileChannel

Java NIO中的FileChannel是一个链接到文件的通道。能够经过文件通道读写文件。缓存

FileChannel没法设置为非阻塞模式,它老是运行在阻塞模式下。dom

打开FileChannel

在使用FileChannel以前,必须先打开它。可是,咱们没法直接打开一个FileChannel,须要经过使用一个InputStream、OutputStream或RandomAccessFile来获取一个FileChannel实例。性能

 

从FileChannel读取数据

调用多个read()方法之一从FileChannel中读取数据。spa

 

首先,分配一个Buffer。从FileChannel中读取的数据将被读到Buffer中。操作系统

而后,调用FileChannel.read()方法。该方法将数据从FileChannel读取到Buffer中。read()方法返回的int值表示了有多少字节被读到了Buffer中。若是返回-1,表示到了文件末尾。指针

向FileChannel写数据

使用FileChannel.write()方法向FileChannel写数据,该方法的参数是一个Buffer。code

 

注意FileChannel.write()是在while循环中调用的。由于没法保证write()方法一次能向FileChannel写入多少字节,所以须要重复调用write()方法,直到Buffer中已经没有还没有写入通道的字节。blog

关闭FileChannel

用完FileChannel后必须将其关闭。如:ip

FileChannel的position方法

有时可能须要在FileChannel的某个特定位置进行数据的读/写操做。能够经过调用position()方法获取FileChannel的当前位置。内存

也能够经过调用position(long pos)方法设置FileChannel的当前位置。

 

若是将位置设置在文件结束符以后,而后试图从文件通道中读取数据,读方法将返回-1 —— 文件结束标志。

若是将位置设置在文件结束符以后,而后向通道中写数据,文件将撑大到当前位置并写入数据。这可能致使“文件空洞”,磁盘上物理文件中写入的数据间有空隙。

FileChannel的size方法

FileChannel实例的size()方法将返回该实例所关联文件的大小。如:

FileChannel的truncate方法

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

这个例子截取文件的前1024个字节。

FileChannel的force方法

FileChannel.force()方法将通道里还没有写入磁盘的数据强制写到磁盘上。出于性能方面的考虑,操做系统会将数据缓存在内存中,因此没法保证写入到FileChannel里的数据必定会即时写到磁盘上。要保证这一点,须要调用force()方法。

force()方法有一个boolean类型的参数,指明是否同时将文件元数据(权限信息等)写到磁盘上。

/**
     * file channel
     */
    @Test
    public void text1() throws IOException {
        //从buffer读
        RandomAccessFile raf = new RandomAccessFile(new File("./test.txt"),"rw");
        FileChannel channel = raf.getChannel();             //获取通道
        channel.position(channel.size());                   //设置文件末尾位置,做为写入初始位置;不带参获取指针位置
        ByteBuffer byteBuffer = ByteBuffer.allocate(1024);  //缓冲区
        byteBuffer.put("456".getBytes());
        byteBuffer.flip();                                  //反转
        while (byteBuffer.hasRemaining()) {                 //判断
            channel.write(byteBuffer);
        }
        channel.truncate(2);                                //截取文件
        channel.force(true);                      //强行写
        raf.close();
        //向buffer写
        raf = new RandomAccessFile(new File("./test.txt"),"rw");
        channel = raf.getChannel();
        byteBuffer = ByteBuffer.allocate(1024);
        int read;
        while ((read = channel.read(byteBuffer))!=-1) {
            byteBuffer.flip();                                  //反转
            while (byteBuffer.hasRemaining()) {                 //判断
                System.err.print((char)byteBuffer.get());       //输出
            }
            byteBuffer.clear();                                 //清除
        }
    }
相关文章
相关标签/搜索