java.nio.channels.FileChannel.force()方法的使用及代码示例

x33g5p2x  于2022-01-18 转载在 其他  
字(10.6k)|赞(0)|评价(0)|浏览(373)

本文整理了Java中java.nio.channels.FileChannel.force()方法的一些代码示例,展示了FileChannel.force()的具体用法。这些代码示例主要来源于Github/Stackoverflow/Maven等平台,是从一些精选项目中提取出来的代码,具有较强的参考意义,能在一定程度帮忙到你。FileChannel.force()方法的具体详情如下:
包路径:java.nio.channels.FileChannel
类名称:FileChannel
方法名:force

FileChannel.force介绍

[英]Requests that all updates to this channel are committed to the storage device.

When this method returns, all modifications made to the platform file underlying this channel have been committed if the file resides on a local storage device. If the file is not hosted locally, for example on a networked file system, then applications cannot be certain that the modifications have been committed.

There are no assurances given that changes made to the file using methods defined elsewhere will be committed. For example, changes made via a mapped byte buffer may not be committed.

The metadata parameter indicates whether the update should include the file's metadata such as last modification time, last access time, etc. Note that passing true may invoke an underlying write to the operating system (if the platform is maintaining metadata such as last access time), even if the channel is opened read-only.
[中]请求将对此通道的所有更新提交到存储设备。
此方法返回时,如果此通道下的平台文件位于本地存储设备上,则对该文件所做的所有修改都已提交。如果文件不是本地托管的,例如在网络文件系统上,则应用程序无法确定修改是否已提交。
无法保证使用其他地方定义的方法对文件所做的更改将被提交。例如,通过映射字节缓冲区进行的更改可能不会提交。
metadata参数指示更新是否应包括文件的元数据,如上次修改时间、上次访问时间等。请注意,传递true可能会调用对操作系统的底层写入(如果平台维护元数据,如上次访问时间),即使通道以只读方式打开。

代码示例

代码示例来源:origin: bumptech/glide

public static void toFile(@NonNull ByteBuffer buffer, @NonNull File file) throws IOException {
 buffer.position(0);
 RandomAccessFile raf = null;
 FileChannel channel = null;
 try {
  raf = new RandomAccessFile(file, "rw");
  channel = raf.getChannel();
  channel.write(buffer);
  channel.force(false /*metadata*/);
  channel.close();
  raf.close();
 } finally {
  if (channel != null) {
   try {
    channel.close();
   } catch (IOException e) {
    // Ignored.
   }
  }
  if (raf != null) {
   try {
    raf.close();
   } catch (IOException e) {
    // Ignored.
   }
  }
 }
}

代码示例来源:origin: apache/ignite

/**
 * Write node id (who captured lock) into lock file.
 *
 * @param content Node id.
 * @throws IOException if some fail while write node it.
 */
private void writeContent(String content) throws IOException {
  FileChannel ch = lockFile.getChannel();
  byte[] bytes = content.getBytes();
  ByteBuffer buf = ByteBuffer.allocate(bytes.length);
  buf.put(bytes);
  buf.flip();
  ch.write(buf, 1);
  ch.force(false);
}

代码示例来源:origin: apache/ignite

/**
   * Write cache to file.
   *
   * @param force force metadata.
   */
  private void flushCache(boolean force) throws IOException {
    if (cache.position() > 0) {
      cache.flip();
      while (cache.remaining() > 0)
        file.getChannel().write(cache);
      cache.clear();
    }
    file.getChannel().force(force);
  }
}

代码示例来源:origin: apache/activemq

private File createJournalTemplateFile() {
  String fileName = "db-log.template";
  File rc = new File(directory, fileName);
  try (RandomAccessFile templateRaf = new RandomAccessFile(rc, "rw");) {
    templateRaf.getChannel().write(ByteBuffer.wrap(EOF_RECORD));
    templateRaf.setLength(maxFileLength);
    templateRaf.getChannel().force(true);
  } catch (FileNotFoundException e) {
    LOG.error("Could not find the template file on disk at " + osKernelCopyTemplateFile.getAbsolutePath(), e);
  } catch (IOException e) {
    LOG.error("Could not transfer the template file to journal, transferFile=" + osKernelCopyTemplateFile.getAbsolutePath(), e);
  }
  return rc;
}

代码示例来源:origin: apache/activemq

private void doPreallocationZeros(RecoverableRandomAccessFile file) {
  preAllocateDirectBuffer.rewind();
  try {
    FileChannel channel = file.getChannel();
    channel.write(preAllocateDirectBuffer);
    channel.force(false);
    channel.position(0);
  } catch (ClosedByInterruptException ignored) {
    LOG.trace("Could not preallocate journal file with zeros", ignored);
  } catch (IOException e) {
    LOG.error("Could not preallocate journal file with zeros", e);
  }
}

代码示例来源:origin: yu199195/hmily

/**
   * Write file.
   *
   * @param fullFileName the full file name
   * @param contents     the contents
   */
  public static void writeFile(final String fullFileName, final byte[] contents) {
    try {
      RandomAccessFile raf = new RandomAccessFile(fullFileName, "rw");
      try (FileChannel channel = raf.getChannel()) {
        ByteBuffer buffer = ByteBuffer.allocate(contents.length);
        buffer.put(contents);
        buffer.flip();
        while (buffer.hasRemaining()) {
          channel.write(buffer);
        }
        channel.force(true);
      }
    } catch (IOException e) {
      e.printStackTrace();
    }
  }
}

代码示例来源:origin: spotify/helios

private AllocatedPort lock(final int port, final String name) {
 final Path path = lockDirectory.resolve(String.valueOf(port));
 try {
  final FileChannel file = FileChannel.open(path, CREATE, WRITE);
  final FileLock lock = file.tryLock();
  if (lock == null) {
   return null;
  }
  file.write(ByteBuffer.wrap(format("%d %s%n", port, name).getBytes(UTF_8)));
  file.force(true);
  return new AllocatedPort(port, path, file, lock);
 } catch (OverlappingFileLockException e) {
  return null;
 } catch (IOException e) {
  log.error("Failed to take port lock: {}", path, e);
  throw new RuntimeException(e);
 }
}

代码示例来源:origin: yu199195/Raincat

private void writeFile(final TransactionRecoverAdapter adapter, final String fullFileName) {
  try {
    RandomAccessFile raf = new RandomAccessFile(fullFileName, "rw");
    try (FileChannel channel = raf.getChannel()) {
      byte[] content = objectSerializer.serialize(adapter);
      ByteBuffer buffer = ByteBuffer.allocate(content.length);
      buffer.put(content);
      buffer.flip();
      while (buffer.hasRemaining()) {
        channel.write(buffer);
      }
      channel.force(true);
    }
  } catch (Exception e) {
    e.printStackTrace();
  }
}

代码示例来源:origin: apache/activemq

private void doPreallocationSparseFile(RecoverableRandomAccessFile file) {
  final ByteBuffer journalEof = ByteBuffer.wrap(EOF_RECORD);
  try {
    FileChannel channel = file.getChannel();
    channel.position(0);
    channel.write(journalEof);
    channel.position(maxFileLength - 5);
    journalEof.rewind();
    channel.write(journalEof);
    channel.force(false);
    channel.position(0);
  } catch (ClosedByInterruptException ignored) {
    LOG.trace("Could not preallocate journal file with sparse file", ignored);
  } catch (IOException e) {
    LOG.error("Could not preallocate journal file with sparse file", e);
  }
}

代码示例来源:origin: wildfly/wildfly

/**
 * {@inheritDoc}
 */
@Override
protected void addResource(XAResource resource, URI uri) throws SystemException {
  assert fileChannel != null;
  try {
    assert fileChannel.isOpen();
    fileChannel.write(ByteBuffer.wrap((uri.toString() + System.lineSeparator()).getBytes(StandardCharsets.UTF_8)));
    fileChannel.force(true);
  } catch (IOException e) {
    throw Log.log.appendXAResourceRecoveryFileFailed(uri, filePath, e);
  }
  this.resources.add(resource);
  Log.log.xaResourceAddedToRecoveryRegistry(uri, filePath);
}

代码示例来源:origin: traccar/traccar

public String writeFile(String uniqueId, ByteBuf buf, String extension) {
  if (path != null) {
    int size = buf.readableBytes();
    String name = new SimpleDateFormat("yyyyMMddHHmmss").format(new Date()) + "." + extension;
    try (FileOutputStream output = new FileOutputStream(createFile(uniqueId, name));
        FileChannel fileChannel = output.getChannel()) {
        ByteBuffer byteBuffer = buf.nioBuffer();
      int written = 0;
      while (written < size) {
        written += fileChannel.write(byteBuffer);
      }
      fileChannel.force(false);
      return name;
    } catch (IOException e) {
      LOGGER.warn("Save media file error", e);
    }
  }
  return null;
}

代码示例来源:origin: apache/activemq

private void doPreallocationChunkedZeros(RecoverableRandomAccessFile file) {
  preAllocateDirectBuffer.limit(preAllocateDirectBuffer.capacity());
  preAllocateDirectBuffer.rewind();
  try {
    FileChannel channel = file.getChannel();
    int remLen = maxFileLength;
    while (remLen > 0) {
      if (remLen < preAllocateDirectBuffer.remaining()) {
        preAllocateDirectBuffer.limit(remLen);
      }
      int writeLen = channel.write(preAllocateDirectBuffer);
      remLen -= writeLen;
      preAllocateDirectBuffer.rewind();
    }
    channel.force(false);
    channel.position(0);
  } catch (ClosedByInterruptException ignored) {
    LOG.trace("Could not preallocate journal file with zeros", ignored);
  } catch (IOException e) {
    LOG.error("Could not preallocate journal file with zeros! Will continue without preallocation", e);
  }
}

代码示例来源:origin: ltsopensource/light-task-scheduler

@Override
public void write(FileChannel fileChannel) throws IOException {
  byteBuffer().position(0);
  byteBuffer().putShort(magic);
  byteBuffer().putLong(storeTxLogRecordId);
  byteBuffer().flip();
  fileChannel.position(0);
  fileChannel.write(byteBuffer());
  fileChannel.force(true);
}

代码示例来源:origin: ltsopensource/light-task-scheduler

@Override
public void write(FileChannel fileChannel) throws IOException {
  byteBuffer().position(0);
  byteBuffer().putShort(magic);
  byteBuffer().putLong(storeTxLogRecordId);
  byteBuffer().flip();
  fileChannel.position(0);
  fileChannel.write(byteBuffer());
  fileChannel.force(true);
}

代码示例来源:origin: ltsopensource/light-task-scheduler

@Override
  public void write(FileChannel fileChannel) throws IOException {
    byteBuffer().position(0);
    byteBuffer().putShort(magic);
    byteBuffer().putLong(this.firstRecordId);
    byteBuffer().flip();

    fileChannel.position(0);
    fileChannel.write(byteBuffer());
    fileChannel.force(true);
  }
}

代码示例来源:origin: spring-projects/spring-batch

private void complete() throws IOException {
  StringBuilder buffer = (StringBuilder) TransactionSynchronizationManager.getResource(bufferKey);
  if (buffer != null) {
    String string = buffer.toString();
    byte[] bytes = string.getBytes(encoding);
    int bufferLength = bytes.length;
    ByteBuffer bb = ByteBuffer.wrap(bytes);
    int bytesWritten = channel.write(bb);
    if(bytesWritten != bufferLength) {
      throw new IOException("All bytes to be written were not successfully written");
    }
    if (forceSync) {
      channel.force(false);
    }
    if (TransactionSynchronizationManager.hasResource(closeKey)) {
      closeCallback.run();
    }
  }
}

代码示例来源:origin: ltsopensource/light-task-scheduler

@Override
  public void write(FileChannel fileChannel) throws IOException {
    byteBuffer().position(0);
    byteBuffer().putShort(magic);
    byteBuffer().putLong(this.firstRecordId);
    byteBuffer().flip();

    fileChannel.position(0);
    fileChannel.write(byteBuffer());
    fileChannel.force(true);
  }
}

代码示例来源:origin: wildfly/wildfly

ByteBuffer byteBuffer = byteBuf.nioBuffer();
  while (written < length) {
    written += fileChannel.write(byteBuffer);
    written += fileChannel.write(byteBuffers);
fileChannel.force(false);
fileChannel.close();
outputStream.close();

代码示例来源:origin: io.netty/netty

public boolean renameTo(File dest) throws IOException {
  if (dest == null) {
    throw new NullPointerException("dest");
  }
  if (channelBuffer == null) {
    // empty file
    dest.createNewFile();
    isRenamed = true;
    return true;
  }
  int length = channelBuffer.readableBytes();
  FileOutputStream outputStream = new FileOutputStream(dest);
  FileChannel fileChannel = outputStream.getChannel();
  ByteBuffer byteBuffer = channelBuffer.toByteBuffer();
  int written = 0;
  while (written < length) {
    written += fileChannel.write(byteBuffer);
  }
  fileChannel.force(false);
  fileChannel.close();
  outputStream.close();
  isRenamed = true;
  return written == length;
}

代码示例来源:origin: ltsopensource/light-task-scheduler

@Override
public void write(FileChannel fileChannel) throws IOException {
  byteBuffer().position(0);
  byteBuffer().putShort(magic);
  byteBuffer().putLong(fileLength);
  byteBuffer().putInt(totalNum.get());
  byteBuffer().putInt(aliveNum.get());
  byteBuffer().putInt(isFull);
  byteBuffer().putLong(storeTxLogRecordId);
  byteBuffer().flip();
  fileChannel.position(0);
  fileChannel.write(byteBuffer());
  fileChannel.force(true);
}

相关文章