Java NIO FileChannel

    技术2022-07-13  85

    Java NIO FileChannel是连接到文件的Channel。使用文件Channel,你可以从文件读取数据,也可以将数据写入文件。 Java NIO FileChannel类是标准Java IO API的一种替代方式。

    无法将FileChannel设置为非阻塞模式,它始终以阻止模式运行。

     

    1.打开一个FileChannel

    在使用FileChannel之前必须打开它。

    你不能直接打开FileChannel,需要通过InputStream,OutputStream或RandomAccessFile获取FileChannel。这是通过RandomAccessFile打开FileChannel的方式:

    RandomAccessFile aFile = new RandomAccessFile("data/nio-data.txt", "rw"); FileChannel inChannel = aFile.getChannel();

     

    2.从FileChannel读取数据

    要从FileChannel读取数据,请调用read()方法:

    ByteBuffer buf = ByteBuffer.allocate(48); int bytesRead = inChannel.read(buf);

     

    首先分配一个Buffer,从FileChannel读取的数据被读到Buffer。

    其次,调用FileChannel.read()方法,此方法将数据从FileChannel读取到Buffer。 read()方法返回的int表示多少字节写到了Buffer中。如果返回-1,则到达文件末尾。

     

    3.将数据写入FileChannel

    使用FileChannel.write()方法(将Buffer作为参数)将数据写入FileChannel:

    String newData = "New String to write to file..." + System.currentTimeMillis(); ByteBuffer buf = ByteBuffer.allocate(48); buf.clear(); buf.put(newData.getBytes()); buf.flip(); while(buf.hasRemaining()) { channel.write(buf); }

     

    注意在while循环中如何调用FileChannel.write()方法。因为无法保证write()方法将多少字节写入FileChannel,所以我们重复执行write()调用,直到Buffer没有要写入的字节为止。

     

    4.关闭FileChannel

    使用FileChannel完成后,必须将其关闭:

    channel.close();

     

    5.FileChannel Position

    读取或写入FileChannel时,是在特定位置进行。可以通过调用position()方法获得FileChannel对象的当前位置。

    你还可以通过调用position(long pos)方法来设置FileChannel的位置。

    long pos = channel.position(); channel.position(pos +123);

     

    如果将位置设置在文件末尾之后,并尝试从通道读取,则会得到-1(文件末尾标记)。

    如果在文件末尾之后设置位置并写入通道,则文件将被扩展以适合位置和写入的数据。这可能会导致“文件漏洞”,磁盘上的物理文件在写入数据中会留有间隙。

     

    6.FileChannel Size

    FileChannel对象的size()方法返回通道连接到的文件的文件大小:

    channel.truncate(1024);

     

    7.FileChannel Truncate

    你可以通过调用FileChannel.truncate()方法来截断文件:

    channel.truncate(1024);

     

    本示例将文件长度截断为1024个字节。

     

    8.FileChannel Force

    FileChannel.force()方法将所有未写入的数据从Channel刷新到磁盘。出于性能原因,操作系统可能会将数据缓存在内存中,因此除非调用force()方法,否则不能保证写入Channel的数据实际上已写入磁盘。

    force()方法接收布尔值参数,表示是否也应刷新文件元数据(权限等)。

    这是刷新数据和元数据的示例:

    channel.force(true);

     

    原文地址: https://www.zhblog.net/go/java/tutorial/java-nio-filechannle?t=615

     

     

    Processed: 0.009, SQL: 9