我正在尝试AsynchronousFileChannel Java7API以异步方式编写文件,但是我找不到一种简单的方式来附加到该文件。
API描述指出,AsynchronousFileChannel不维护文件位置,您必须指定文件位置。这意味着您必须维护一个全局文件位置值。此外,这个全局状态应该是原子的,这样您就可以正确地递增。
是否有更好的使用AsynchronousFileChannel进行更新的方法?
另外,有人能解释一下API中附件对象的用法吗?
public abstract <A> void write(ByteBuffer src,
long position,
A attachment,
CompletionHandler<Integer ,? super A> handler)javadoc说:附件-要附加到I/O操作的对象;可以为空。
这个附件对象的用途是什么?
谢谢!
发布于 2015-07-23 15:28:54
这个附件对象的用途是什么?
附件是可以传递给完成处理程序的对象;将其视为提供上下文的机会。您几乎可以将它用于您所能想象的任何事情,从日志记录到同步,或者只是简单地忽略它。
我正在尝试AsynchronousFileChannel Java7API以异步方式编写文件,但是我找不到一种简单的方式来附加到该文件。
异步通常有点棘手,并且附加到文件中是一个固有的串行进程。这就是说,您可以并行完成,但是您必须做一些簿记,以便在哪里追加下一个缓冲区内容。我想它可能看起来像这样(使用频道本身作为“附件”):
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) );
}
}发布于 2015-08-16 15:58:04
我刚用channel.size()作为位置。在我的例子中,文件不是由多个线程移动的,只有一个线程打开并写入文件,到目前为止,这似乎是可行的。
如果有人知道这是一件错误的事情,请插嘴。
https://stackoverflow.com/questions/20791178
复制相似问题