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

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

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

FileChannel.read介绍

[英]Reads bytes from this file channel and stores them in the specified array of buffers. This method attempts to read as many bytes as can be stored in the buffer array from this channel and returns the number of bytes actually read. It also increases the file position by the number of bytes read.

If a read operation is in progress, subsequent threads will block until the read is completed and will then contend for the ability to read.

Calling this method is equivalent to calling read(buffers, 0, buffers.length);
[中]从该文件通道读取字节并将其存储在指定的缓冲区数组中。此方法尝试从此通道读取缓冲区数组中存储的尽可能多的字节,并返回实际读取的字节数。它还将文件位置增加读取的字节数。
如果读取操作正在进行,后续线程将阻塞,直到读取完成,然后争夺读取能力。
调用此方法相当于调用read(buffers,0,buffers.length);

代码示例

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

private static byte[] readBytesFromFileInputStream(FileInputStream fis) throws IOException
{
  FileChannel channel = fis.getChannel();
  int fileSize = (int) channel.size();
  ByteBuffer byteBuffer = ByteBuffer.allocate(fileSize);
  channel.read(byteBuffer);
  byteBuffer.flip();
  byte[] bytes = byteBuffer.array();
  byteBuffer.clear();
  channel.close();
  fis.close();
  return bytes;
}

代码示例来源:origin: Tencent/tinker

public static void readUntilLimit(FileChannel channel, ByteBuffer bufferOut, String errMsg) throws IOException {
  bufferOut.rewind();
  int bytesRead = channel.read(bufferOut);
  if (bytesRead != bufferOut.limit()) {
    throw new IOException(errMsg + " Rest bytes insufficient, expect to read "
        + bufferOut.limit() + " bytes but only "
        + bytesRead + " bytes were read.");
  }
  bufferOut.flip();
}

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

@Override
public int read() throws IOException {
  if (buffer == null) {
    buffer = ByteBuffer.allocate(1);
  }
  buffer.rewind();
  int len = channel.read(buffer, pos++);
  if (len < 0) {
    return -1;
  }
  return buffer.get(0) & 0xff;
}

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

/**
 * Read an ndarray from disk
 * @param readFrom
 * @return
 * @throws IOException
 */
public static INDArray readFromDisk(File readFrom) throws IOException {
  try (FileInputStream os = new FileInputStream(readFrom)) {
    FileChannel channel = os.getChannel();
    ByteBuffer buffer = ByteBuffer.allocateDirect((int) readFrom.length());
    channel.read(buffer);
    INDArray ret = toArray(buffer);
    return ret;
  }
}

代码示例来源:origin: jeremylong/DependencyCheck

/**
 * <p>
 * Creates the cryptographic checksum of a given file using the specified
 * algorithm.</p>
 *
 * @param algorithm the algorithm to use to calculate the checksum
 * @param file the file to calculate the checksum for
 * @return the checksum
 * @throws IOException when the file does not exist
 * @throws NoSuchAlgorithmException when an algorithm is specified that does
 * not exist
 */
public static byte[] getChecksum(String algorithm, File file) throws NoSuchAlgorithmException, IOException {
  final MessageDigest md = MessageDigest.getInstance(algorithm);
  try (FileInputStream fis = new FileInputStream(file);
      FileChannel ch = fis.getChannel()) {
    final ByteBuffer buf = ByteBuffer.allocateDirect(8192);
    int b = ch.read(buf);
    while (b != -1 && b != 0) {
      buf.flip();
      final byte[] bytes = new byte[b];
      buf.get(bytes);
      md.update(bytes, 0, b);
      buf.clear();
      b = ch.read(buf);
    }
    return md.digest();
  }
}

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

/**
 * Utility function
 * @return the array of bytes
 */
private static byte[] readFrom(File src) throws IOException {
  long srcsize = src.length();
  if (srcsize > Integer.MAX_VALUE) {
    throw new IllegalArgumentException(
        "File too big to be loaded in memory");
  }
  FileInputStream inputStream = new FileInputStream(src);
  byte[] array = new byte[(int) srcsize];
  try {
    FileChannel fileChannel = inputStream.getChannel();
    ByteBuffer byteBuffer = ByteBuffer.wrap(array);
    int read = 0;
    while (read < srcsize) {
      read += fileChannel.read(byteBuffer);
    }
  } finally {
    inputStream.close();
  }
  return array;
}

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

ByteBuffer byteBuffer = ByteBuffer.allocate(Math.min(availableBytes, offset));
int readBytes = fileChannel.read(byteBuffer);
if (readBytes == availableBytes)
byteBuffer.flip();
byte[] bytes = byteBuffer.array();
System.arraycopy(this.bytes, offset, this.bytes, offset - readBytes, bufferSize - offset);

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

@Override
public int setBytes(int index, FileChannel in, long position, int length) throws IOException {
  ensureAccessible();
  ByteBuffer tmpBuf = internalNioBuffer();
  tmpBuf.clear().position(index).limit(index + length);
  try {
    return in.read(tmpNioBuf, position);
  } catch (ClosedChannelException ignored) {
    return -1;
  }
}

代码示例来源:origin: qunarcorp/qmq

private boolean reAlloc() {
  try {
    buffer.clear();
    int bytes = fileChannel.read(buffer, visited.get());
    if (bytes > 0) {
      buffer.flip();
      visitedSnapshot.addAndGet(visited.get() - visitedSnapshot.get());
      return true;
    }
  } catch (IOException e) {
    LOGGER.error("load visitor nextRecord error", e);
  }
  return false;
}

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

/**
 *
 */
private String readContent() throws IOException {
  FileChannel ch = lockFile.getChannel();
  ByteBuffer buf = ByteBuffer.allocate((int)(ch.size() - 1));
  ch.read(buf, 1);
  String content = new String(buf.array());
  buf.clear();
  return content;
}

代码示例来源:origin: qunarcorp/qmq

AbstractLogVisitor(long from, FileChannel fileChannel, int workingSize) {
  this.fileChannel = fileChannel;
  this.visited = new AtomicLong(from);
  this.visitedSnapshot = new AtomicLong(from);
  buffer = ByteBuffer.allocateDirect(workingSize);
  try {
    fileChannel.read(buffer, visited.get());
    buffer.flip();
  } catch (IOException e) {
    LOGGER.error("load dispatch log visitor error", e);
  }
}

代码示例来源:origin: org.apache.hadoop/hadoop-common

@Override
public int read(long position, byte[] b, int off, int len)
 throws IOException {
 // parameter check
 validatePositionedReadArgs(position, b, off, len);
 if (len == 0) {
  return 0;
 }
 ByteBuffer bb = ByteBuffer.wrap(b, off, len);
 try {
  int value = fis.getChannel().read(bb, position);
  if (value > 0) {
   statistics.incrementBytesRead(value);
  }
  return value;
 } catch (IOException e) {
  throw new FSError(e);
 }
}

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

public static ByteArrayFileStream createByteArrayFileStream(FileInputStream fileInputStream) throws IOException
{
  FileChannel channel = fileInputStream.getChannel();
  long size = channel.size();
  int bufferSize = (int) Math.min(1048576, size);
  ByteBuffer byteBuffer = ByteBuffer.allocate(bufferSize);
  if (channel.read(byteBuffer) == size)
  {
    channel.close();
    channel = null;
  }
  byteBuffer.flip();
  byte[] bytes = byteBuffer.array();
  return new ByteArrayFileStream(bytes, bufferSize, channel);
}

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

try (FileInputStream os = new FileInputStream(readFrom)) {
  FileChannel channel = os.getChannel();
  channel.read(buffer);

代码示例来源:origin: pinterest/secor

@Override
  public void run() {
    try {
      if (directUpload) {
        byte[] content = Files.readAllBytes(localFile.toPath());
        Blob result = mClient.create(sourceBlob, content);
        LOG.debug("Upload file {} to gs://{}/{}", localFile, gsBucket, gsKey);
        LOG.trace("Upload file {}, Blob: {}", result);
      } else {
        long startTime = System.nanoTime();
        try (WriteChannel out = mClient.writer(sourceBlob);
          FileChannel in = new FileInputStream(localFile).getChannel();
          ) {
          ByteBuffer buffer = ByteBuffer.allocateDirect(1024 * 1024 * 5); // 5 MiB buffer (remember this is pr. thread)
          int bytesRead;
          while ((bytesRead = in.read(buffer)) > 0) {
            buffer.flip();
            out.write(buffer);
            buffer.clear();
          }
        }
        long elapsedTime = System.nanoTime() - startTime;
        LOG.debug("Upload file {} to gs://{}/{} in {} msec", localFile, gsBucket, gsKey, (elapsedTime / 1000000.0));
      }
    } catch (IOException e) {
      throw new RuntimeException(e);
    }
  }
});

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

/**
 * Utility function
 * @return the array of bytes
 */
private static byte[] readFrom(File src) throws IOException {
  long srcsize = src.length();
  if (srcsize > Integer.MAX_VALUE) {
    throw new IllegalArgumentException(
        "File too big to be loaded in memory");
  }
  FileInputStream inputStream = new FileInputStream(src);
  FileChannel fileChannel = inputStream.getChannel();
  byte[] array = new byte[(int) srcsize];
  ByteBuffer byteBuffer = ByteBuffer.wrap(array);
  int read = 0;
  while (read < srcsize) {
    read += fileChannel.read(byteBuffer);
  }
  fileChannel.close();
  return array;
}

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

FileChannel ch = raf.getChannel();
ByteBuffer buf = ByteBuffer.allocate(DFLT_BUFFER_SIZE);
ch.read(buf);
buf.flip();

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

/**
 * 读取指定位置数据
 */
public byte[] readData(long fromIndex, int length) throws IOException {
  fileChannel.position(fromIndex);
  ByteBuffer byteBuffer = ByteBuffer.allocate(length);
  fileChannel.read(byteBuffer);
  return byteBuffer.array();
}

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

@Override
public int setBytes(int index, FileChannel in, long position, int length) throws IOException {
  ensureAccessible();
  try {
    return in.read((ByteBuffer) internalNioBuffer().clear().position(index).limit(index + length), position);
  } catch (ClosedChannelException ignored) {
    return -1;
  }
}

代码示例来源:origin: org.apache.spark/spark-core

/**
 * Checks weather data is left to be read from the input stream.
 * @return true if data is left, false otherwise
 * @throws IOException
 */
private boolean refill() throws IOException {
 if (!byteBuffer.hasRemaining()) {
  byteBuffer.clear();
  int nRead = 0;
  while (nRead == 0) {
   nRead = fileChannel.read(byteBuffer);
  }
  if (nRead < 0) {
   return false;
  }
  byteBuffer.flip();
 }
 return true;
}

相关文章