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

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

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

FileChannel.write介绍

[英]Writes bytes from all the given byte buffers to this file channel.

The bytes are written starting at the current file position, and after the bytes are written (up to the remaining number of bytes in all the buffers), the file position is increased by the number of bytes actually written.

Calling this method is equivalent to calling write(buffers, 0, buffers.length);
[中]将所有给定字节缓冲区中的字节写入此文件通道。
从当前文件位置开始写入字节,写入字节后(直到所有缓冲区中剩余的字节数),文件位置将增加实际写入的字节数。
调用此方法相当于调用write(buffers,0,buffers.length);

代码示例

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

@Override
  public void write(byte[] bytes, int offset, int length) throws IOException {
    while (length > 0) {
      int n = writeChannel.write(ByteBuffer.wrap(bytes, offset, length), writeOffset);
      offset += n;
      length -= n;
      writeOffset += n;
    }
  }
};

代码示例来源:origin: blynkkk/blynk-server

private static void write(File file, ByteBuffer data) throws Exception {
  try (FileChannel channel = new FileOutputStream(file, false).getChannel()) {
    channel.write(data);
  }
}

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

public boolean appendMessage(final byte[] data) {
  int currentPos = this.wrotePosition.get();
  if ((currentPos + data.length) <= this.fileSize) {
    try {
      this.fileChannel.position(currentPos);
      this.fileChannel.write(ByteBuffer.wrap(data));
    } catch (Throwable e) {
      log.error("Error occurred when append message to mappedFile.", e);
    }
    this.wrotePosition.addAndGet(data.length);
    return true;
  }
  return false;
}

代码示例来源:origin: hankcs/HanLP

/**
 * 快速保存
 *
 * @param path
 * @param content
 * @return
 */
public static boolean saveTxt(String path, String content)
{
  try
  {
    FileChannel fc = new FileOutputStream(path).getChannel();
    fc.write(ByteBuffer.wrap(content.getBytes()));
    fc.close();
  }
  catch (Exception e)
  {
    logger.throwing("IOUtil", "saveTxt", e);
    logger.warning("IOUtil saveTxt 到" + path + "失败" + e.toString());
    return false;
  }
  return 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: 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: alibaba/fescar

private boolean writeDataFile(byte[] bs) {
  int retry = 0;
  byte[] byWrite = new byte[bs.length + 4];
  ByteBuffer byteBuffer = ByteBuffer.wrap(byWrite);
  byteBuffer.putInt(bs.length);
  byteBuffer.put(bs);
  for (; retry < MAX_WRITE_RETRY; retry++) {
    try {
      byteBuffer.flip();
      while (byteBuffer.hasRemaining()) {
        currFileChannel.write(byteBuffer);
      }
      return true;
    } catch (IOException exx) {
      LOGGER.error("write data file error:" + exx.getMessage());
    }
  }
  LOGGER.error("write dataFile failed,retry more than :" + MAX_WRITE_RETRY);
  return false;
}

代码示例来源:origin: com.h2database/h2

@Override
public int write(ByteBuffer src) throws IOException {
  byte[] buff = src.array();
  int len = src.remaining();
  if (src.position() != 0 || len != buff.length) {
    int offset = src.arrayOffset() + src.position();
    buff = Arrays.copyOfRange(buff, offset, offset + len);
  }
  int result = channel.write(src);
  rec.log(Recorder.WRITE, name, buff, channel.position());
  return result;
}

代码示例来源:origin: zhegexiaohuozi/SeimiCrawler

public void saveTo(File targetFile) {
  try (
      FileOutputStream fileOutputStream = new FileOutputStream(targetFile);
      FileChannel fo = fileOutputStream.getChannel()
  ) {
    File pf = targetFile.getParentFile();
    if (!pf.exists()) {
      pf.mkdirs();
    }
    if (BodyType.TEXT.equals(bodyType)) {
      fo.write(ByteBuffer.wrap(getContent().getBytes()));
    } else {
      fo.write(ByteBuffer.wrap(getData()));
    }
  } catch (Exception e) {
    throw new SeimiProcessExcepiton(e);
  }
}

代码示例来源:origin: deeplearning4j/nd4j

/**
 * Write an ndarray to disk in
 * binary format
 * @param arr the array to write
 * @param toWrite the file tow rite to
 * @throws IOException
 */
public static void writeArrayToDisk(INDArray arr, File toWrite) throws IOException {
  try (FileOutputStream os = new FileOutputStream(toWrite)) {
    FileChannel channel = os.getChannel();
    ByteBuffer buffer = BinarySerde.toByteBuffer(arr);
    channel.write(buffer);
  }
}

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

/** {@inheritDoc} */
@Override public int write(byte[] buf, int off, int len) throws IOException {
  return ch.write(ByteBuffer.wrap(buf, off, len));
}

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

/**
 * Content of data from offset to offset + length will be wrote to file.
 *
 * @param offset The offset of the subarray to be used.
 * @param length The length of the subarray to be used.
 */
public boolean appendMessage(final byte[] data, final int offset, final int length) {
  int currentPos = this.wrotePosition.get();
  if ((currentPos + length) <= this.fileSize) {
    try {
      this.fileChannel.position(currentPos);
      this.fileChannel.write(ByteBuffer.wrap(data, offset, length));
    } catch (Throwable e) {
      log.error("Error occurred when append message to mappedFile.", e);
    }
    this.wrotePosition.addAndGet(length);
    return true;
  }
  return false;
}

代码示例来源: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: 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: pentaho/pentaho-kettle

private void write( byte[] content ) throws IOException {
 if ( content == null || content.length == 0 ) {
  return;
 }
 // If exceptionally we have a block of data larger than the buffer simply dump it to disk!
 //
 if ( content.length > data.byteBuffer.capacity() ) {
  // It should be exceptional to have a single field containing over 50k data
  //
  ByteBuffer buf = ByteBuffer.wrap( content ); // slow method!
  data.byteBuffer.flip();
  data.fileChannel.write( buf );
 } else {
  // Normal situation, is there capacity in the buffer?
  //
  if ( data.byteBuffer.remaining() > content.length ) {
   // Yes, there is room: add content to buffer
   //
   data.byteBuffer.put( content );
  } else {
   // No: empty the buffer to disk
   //
   data.byteBuffer.flip();
   data.fileChannel.write( data.byteBuffer );
   data.byteBuffer.clear();
   data.byteBuffer.put( content );
  }
 }
}

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

/**
 * pad the current file to increase its size to the next multiple of preAllocSize greater than the current size and position
 *
 * @param fileChannel the fileChannel of the file to be padded
 * @throws IOException
 */
long padFile(FileChannel fileChannel) throws IOException {
  long newFileSize = calculateFileSizeWithPadding(fileChannel.position(), currentSize, preAllocSize);
  if (currentSize != newFileSize) {
    fileChannel.write((ByteBuffer) fill.position(0), newFileSize - fill.remaining());
    currentSize = newFileSize;
  }
  return currentSize;
}

代码示例来源:origin: alibaba/nacos

ByteBuffer data = ByteBuffer.wrap(JSON.toJSONString(datum).getBytes("UTF-8"));
  fc = new FileOutputStream(cacheFile, false).getChannel();
  fc.write(data, data.position());
  fc.force(true);
} catch (Exception e) {

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

public static void copy(File source, File dest) throws IOException {
  FileChannel in = null, out = null;
  try {
    System.out.println("copying: " + source + "\n    --> " + dest);
    in = new FileInputStream(source).getChannel();
    out = new FileOutputStream(dest).getChannel();
    MappedByteBuffer buf = in.map(FileChannel.MapMode.READ_ONLY, 0, in.size());
    out.write(buf);
  } catch (Exception e) {
    System.out.println("Error copying file " + source.getAbsolutePath() + " to " + dest.getAbsolutePath() + " : "
        + e.getMessage());
    throw new IOException();
  } finally {
    FileUtils.close(in, out);
  }
}

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

public int write(long diskOffset, byte[] bytes, int offset, int length) throws IOException {
  synchronized (lock) {
    int n = writeChannel.write(ByteBuffer.wrap(bytes, offset, length), diskOffset);
    tailOffset = Math.max(diskOffset + n, tailOffset);
    return n;
  }
}

代码示例来源: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);
  }
}

相关文章