zoukankan      html  css  js  c++  java
  • 八、Java NIO FileChannel

    所有文章

    https://www.cnblogs.com/lay2017/p/12901123.html

    正文

    Java NIO软件包中的FileChannel表示的是连接到文件上的通道。使用FileChannel,你可以从文件中读取数据,以及写入数据到文件中。

    FileChannel不可以被设置为非阻塞模式,它总是以阻塞模式运行

    打开一个FileChannel

    在使用FileChannel之前,你需要打开它。你无法直接打开FileChannel,只能通过InputStream、OutputStream或者RandomAccessFile,例如

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

    从FileChannel读取数据

    想要读取数据,你需要调用read方法

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

    写入数据到FileChannel

    想要写入数据,你需要调用write方法

    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);
    }

    关闭FileChannel

    channel.close();

    FileChannel的Position

    当读取或者写入数据到FileChannel的时候,你是在一个特定的位置(position)上操作的。你可以获取当前的position,通过position()方法。

    你也可以设置position,通过position(long pos)方法

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

    如果你设置position为文件的最后一个位置,那么read操作将返回-1.

    如果设置破事同你为文件的最后一个位置,那么write操作将会扩大文件大小并写入数据。这可能导致"文件空洞",硬盘上的物理文件包含的写入数据可能存在缺口。

    FileChannel的size

    size方法可以获取文件的大小

    long fileSize = channel.size();

    FileChannel的truncate

    你可以删除文件内容通过truncate方法。

    channel.truncate(1024);

    这里删除了指定的1024字节长度的文件

    FileChannel的force

    force方法将会把内存中的数据flush到硬盘上,如果不调用force方法,你无法保证Channel中的数据都写入到了硬盘上。

    force方法可以传入一个boolean参数,表示是否文件的元数据(例如:权限)也需要一起flush

    channel.force(true);
  • 相关阅读:
    streamsets 集成 cratedb 测试
    streamsets k8s 部署试用
    streamsets rest api 转换 graphql
    StreamSets sdc rpc 测试
    StreamSets 相关文章
    StreamSets 多线程 Pipelines
    StreamSets SDC RPC Pipelines说明
    StreamSets 管理 SDC Edge上的pipeline
    StreamSets 部署 Pipelines 到 SDC Edge
    StreamSets 设计Edge pipeline
  • 原文地址:https://www.cnblogs.com/lay2017/p/12906597.html
Copyright © 2011-2022 走看看