首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >附加到带有Java 7 AsynchronousFileChannel的文件中

附加到带有Java 7 AsynchronousFileChannel的文件中
EN

Stack Overflow用户
提问于 2013-12-26 20:59:55
回答 2查看 2.4K关注 0票数 4

我正在尝试AsynchronousFileChannel Java7API以异步方式编写文件,但是我找不到一种简单的方式来附加到该文件。

API描述指出,AsynchronousFileChannel不维护文件位置,您必须指定文件位置。这意味着您必须维护一个全局文件位置值。此外,这个全局状态应该是原子的,这样您就可以正确地递增。

是否有更好的使用AsynchronousFileChannel进行更新的方法?

另外,有人能解释一下API中附件对象的用法吗?

代码语言:javascript
复制
public abstract <A> void write(ByteBuffer  src,
             long position,
             A attachment,
             CompletionHandler<Integer ,? super A> handler)

javadoc说:附件-要附加到I/O操作的对象;可以为空。

这个附件对象的用途是什么?

谢谢!

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2015-07-23 15:28:54

这个附件对象的用途是什么?

附件是可以传递给完成处理程序的对象;将其视为提供上下文的机会。您几乎可以将它用于您所能想象的任何事情,从日志记录到同步,或者只是简单地忽略它。

我正在尝试AsynchronousFileChannel Java7API以异步方式编写文件,但是我找不到一种简单的方式来附加到该文件。

异步通常有点棘手,并且附加到文件中是一个固有的串行进程。这就是说,您可以并行完成,但是您必须做一些簿记,以便在哪里追加下一个缓冲区内容。我想它可能看起来像这样(使用频道本身作为“附件”):

代码语言:javascript
复制
class WriteOp implements CompletionHandler<Integer, AsynchronousFileChannel> {
  private final ByteBuffer buf;
  private long position;

  WriteOp(ByteBuffer buf, long position) {
    this.buf = buf;
    this.position = position;
  }

  public void completed(Integer result, AsynchronousFileChannel channel) {
    if ( buf.hasRemaining() ) { // incomplete write
      position += result;
      channel.write( buf, position, channel, this );
    }
  }

  public void failed(Throwable ex, AsynchronousFileChannel channel) {
    // ?
  }
}

class AsyncAppender {
  private final AsynchronousFileChannel channel;
  /** Where new append operations are told to start writing. */
  private final AtomicLong projectedSize;

  AsyncAppender(AsynchronousFileChannel channel) throws IOException {
    this.channel = channel;
    this.projectedSize = new AtomicLong(channel.size());
  }

  public void append(ByteBuffer buf) {
    final int buflen = buf.remaining();
    long size;
    do {
      size = projectedSize.get();
    while ( !projectedSize.compareAndSet(size, size + buflen) );

    channel.write( buf, position, channel, new WriteOp(buf, size) );
  }
}
票数 3
EN

Stack Overflow用户

发布于 2015-08-16 15:58:04

我刚用channel.size()作为位置。在我的例子中,文件不是由多个线程移动的,只有一个线程打开并写入文件,到目前为止,这似乎是可行的。

如果有人知道这是一件错误的事情,请插嘴。

票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/20791178

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档