java.nio.channels.FileChannel类的使用及代码示例

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

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

FileChannel介绍

[英]An abstract channel type for interaction with a platform file.

A FileChannel defines the methods for reading, writing, memory mapping, and manipulating the logical state of a platform file. This type does not have a method for opening files, since this behavior has been delegated to the java.io.FileInputStream, java.io.FileOutputStream and java.io.RandomAccessFile types.

FileChannels created from a FileInputStream or a RandomAccessFile created in mode "r", are read-only. FileChannels created from a FileOutputStream are write-only. FileChannels created from a RandomAccessFile created in mode "rw" are read/write. FileChannels created from a RandomAccessFile that was opened in append-mode will also be in append-mode -- meaning that each write will be proceeded by a seek to the end of file.

FileChannels have a virtual pointer into the file which is referred to as a file position. The position can be manipulated by moving it within the file, and the current position can be queried.

FileChannels also have an associated size. The size of the file is the number of bytes that it currently contains. The size can be manipulated by adding more bytes to the end of the file (which increases the size) or truncating the file (which decreases the size). The current size can also be queried.

FileChannels have operations beyond the simple read, write, and close. They can also:

  • request that cached data be forced onto the disk,
  • lock ranges of bytes associated with the file,
  • transfer data directly to another channel in a manner that has the potential to be optimized by the platform,
  • memory-mapping files into NIO buffers to provide efficient manipulation of file data,
  • read and write to the file at absolute byte offsets in a fashion that does not modify the current position.

FileChannels are thread-safe. Only one operation involving manipulation of the file position may be executed at the same time. Subsequent calls to such operations will block, and one of those blocked will be freed to continue when the first operation has completed. There is no ordered queue or fairness applied to the blocked threads.

It is undefined whether operations that do not manipulate the file position will also block when there are any other operations in-flight.

The logical view of the underlying file is consistent across all FileChannels and I/O streams opened on the same file by the same VM. Therefore, modifications performed via a channel will be visible to the stream and vice versa; this includes modifications to the file position, content, size, etc.
[中]用于与平台文件交互的抽象通道类型。
FileChannel定义读取、写入、内存映射和操作平台文件逻辑状态的方法。此类型没有打开文件的方法,因为此行为已委托给java。木卫一。FileInputStream,java。木卫一。FileOutputStream和java。木卫一。随机访问文件类型。
从FileInputStream或在“r”模式下创建的RandomAccessFile创建的文件通道是只读的。从FileOutputStream创建的FileChannel是只读的。从“rw”模式下创建的RandomAccessFile创建的文件通道是读/写的。从在追加模式下打开的RandomAccessFile创建的FileChannel也将处于追加模式——这意味着每次写入都将通过查找继续到文件末尾。
文件通道有一个指向文件的虚拟指针,该文件称为文件位置。可以通过在文件中移动位置来操纵该位置,并且可以查询当前位置。
文件通道还具有关联的大小。文件的大小是它当前包含的字节数。可以通过向文件末尾添加更多字节(增加大小)或截断文件(减小大小)来控制大小。还可以查询当前大小。
FileChannel的操作超出了简单的读、写和关闭。他们还可以:
*请求将缓存的数据强制加载到磁盘上,
*锁定与文件关联的字节范围,
*以平台可能优化的方式将数据直接传输到另一个通道,
*内存将文件映射到NIO缓冲区,以提供对文件数据的有效操作,
*以不修改当前位置的方式以绝对字节偏移量读取和写入文件。
文件通道是线程安全的。同时只能执行一个涉及文件位置操纵的操作。对此类操作的后续调用将被阻止,其中一个被阻止的调用将被释放,以便在第一个操作完成后继续。没有对被阻止的线程应用有序队列或公平性。
未定义在进行任何其他操作时,不操纵文件位置的操作是否也会阻塞。
基础文件的逻辑视图在同一VM在同一文件上打开的所有文件通道和I/O流中都是一致的。因此,经由信道执行的修改将对流可见,反之亦然;这包括对文件位置、内容、大小等的修改。

代码示例

代码示例来源: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: stackoverflow.com

final FileChannel channel = new FileInputStream(fileName).getChannel();
MappedByteBuffer buffer = channel.map(FileChannel.MapMode.READ_ONLY, 0, channel.size());

// when finished
channel.close();

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

private int getBytes(int index, FileChannel out, long position, int length, boolean internal) throws IOException {
  ensureAccessible();
  if (length == 0) {
    return 0;
  }
  ByteBuffer tmpBuf = internal ? internalNioBuffer() : buffer.duplicate();
  tmpBuf.clear().position(index).limit(index + length);
  return out.write(tmpBuf, position);
}

代码示例来源:origin: jenkinsci/jenkins

@Override
  public void close() throws IOException {
    if(channel.isOpen()) {
      if (forceOnClose) {
        channel.force(true);
      }
      channel.close();
    }
  }
}

代码示例来源:origin: square/okio

@Override public long read(Buffer sink, long byteCount) throws IOException {
 if (!channel.isOpen()) throw new IllegalStateException("closed");
 if (position == channel.size()) return -1L;
 long read = channel.transferTo(position, byteCount, sink);
 position += read;
 return read;
}

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

/**
 * Attempt to read a file as a string
 * @throws IOException
 */
public static String readFileAsString(String path, Charset charset) throws IOException {
  if (charset == null) charset = Charset.defaultCharset();
  try (FileChannel fc = FileChannel.open(Paths.get(path))) {
    MappedByteBuffer bb = fc.map(FileChannel.MapMode.READ_ONLY, 0, fc.size());
    return charset.decode(bb).toString();
  }
}

代码示例来源:origin: stackoverflow.com

public static void copyFile( File from, File to ) throws IOException {

  if ( !to.exists() ) { to.createNewFile(); }

  try (
    FileChannel in = new FileInputStream( from ).getChannel();
    FileChannel out = new FileOutputStream( to ).getChannel() ) {

    out.transferFrom( in, 0, in.size() );
  }
}

代码示例来源:origin: stackoverflow.com

URL website = new URL("http://www.website.com/information.asp");
ReadableByteChannel rbc = Channels.newChannel(website.openStream());
FileOutputStream fos = new FileOutputStream("information.html");
fos.getChannel().transferFrom(rbc, 0, Long.MAX_VALUE);

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

/**
 * @param igniteUrl Url to ignite.
 * @return Ignite file name.
 */
private String downloadIgnite(String igniteUrl) {
  try {
    URL url = new URL(igniteUrl);
    HttpURLConnection conn = (HttpURLConnection)url.openConnection();
    int code = conn.getResponseCode();
    if (code == 200) {
      String fileName = fileName(url.toString());
      String filePath = props.igniteLocalWorkDir() + File.separator + fileName;
      if (new File(filePath).exists())
        return fileName;
      FileOutputStream outFile = new FileOutputStream(filePath);
      outFile.getChannel().transferFrom(Channels.newChannel(conn.getInputStream()), 0, Long.MAX_VALUE);
      outFile.close();
      return fileName;
    }
    else
      throw new RuntimeException("Got unexpected response code. Response code: " + code);
  }
  catch (IOException e) {
    throw new RuntimeException("Failed update ignite.", e);
  }
}

代码示例来源:origin: stackoverflow.com

public void copy(File src, File dst) throws IOException {
  FileInputStream inStream = new FileInputStream(src);
  FileOutputStream outStream = new FileOutputStream(dst);
  FileChannel inChannel = inStream.getChannel();
  FileChannel outChannel = outStream.getChannel();
  inChannel.transferTo(0, inChannel.size(), outChannel);
  inStream.close();
  outStream.close();
}

代码示例来源:origin: stackoverflow.com

public static void copyFdToFile(FileDescriptor src, File dst) throws IOException {
  FileChannel inChannel = new FileInputStream(src).getChannel();
  FileChannel outChannel = new FileOutputStream(dst).getChannel();
  try {
    inChannel.transferTo(0, inChannel.size(), outChannel);
  } finally {
    if (inChannel != null)
      inChannel.close();
    if (outChannel != null)
      outChannel.close();
  }
}

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

public static void main(String[] args) throws IOException {
  // trying FileLock mechanics in different processes
  File file = new File("tmp.lock");
  file.createNewFile();
  FileChannel channel = new RandomAccessFile(file, "r").getChannel();
  boolean shared = true;
  FileLock lock1 = channel.tryLock(0, Long.MAX_VALUE, shared);
  System.out.println("locked " + lock1);
  System.in.read();
  System.out.println("release " + lock1);
  lock1.release();
}

代码示例来源:origin: android-hacker/VirtualXposed

public static void writeToFile(byte[] data, File target) throws IOException {
  FileOutputStream fo = null;
  ReadableByteChannel src = null;
  FileChannel out = null;
  try {
    src = Channels.newChannel(new ByteArrayInputStream(data));
    fo = new FileOutputStream(target);
    out = fo.getChannel();
    out.transferFrom(src, 0, data.length);
  } finally {
    if (fo != null) {
      fo.close();
    }
    if (src != null) {
      src.close();
    }
    if (out != null) {
      out.close();
    }
  }
}

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

public synchronized void writeToConfigXmlFile(String content) {
  FileChannel channel = null;
  FileOutputStream outputStream = null;
  FileLock lock = null;
  try {
    RandomAccessFile randomAccessFile = new RandomAccessFile(fileLocation(), "rw");
    channel = randomAccessFile.getChannel();
    lock = channel.lock();
    randomAccessFile.seek(0);
    randomAccessFile.setLength(0);
    outputStream = new FileOutputStream(randomAccessFile.getFD());
    IOUtils.write(content, outputStream, UTF_8);
  } catch (Exception e) {
    throw new RuntimeException(e);
  } finally {
    if (channel != null && lock != null) {
      try {
        lock.release();
        channel.close();
        IOUtils.closeQuietly(outputStream);
      } catch (IOException e) {
        LOGGER.error("Error occured when releasing file lock and closing file.", e);
      }
    }
  }
}

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

public void seek(long seekBytes) throws FileNotFoundException, IOException, InterruptedException {
  fileInput = new FileInputStream(file);
  fileChannel = fileInput.getChannel();
  try {
    fileChannel.position(seekBytes);
  } catch (ClosedByInterruptException e) {
    throw new InterruptedException();
  }
  bufferedInput = new BufferedInputStream(fileInput, size);
  dataInput = new DataInputStream(bufferedInput);
  offset = seekBytes;
}

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

void addPatchFile(String zipFileName) throws IOException {
  File file = new File(zipFileName);
  RandomAccessFile f = new RandomAccessFile(file, "r");
  long fileLength = f.length();
    f.close();
    throw new java.io.IOException();
  MappedByteBuffer directoryMap = f.getChannel().map(
      FileChannel.MapMode.READ_ONLY, dirOffset, dirSize);
  directoryMap.order(ByteOrder.LITTLE_ENDIAN);
    if (directoryMap.getInt(currentOffset) != kCDESignature) {
      Log.w(LOG_TAG, "Missed a central dir sig (at " + currentOffset
          + ")");
        .getShort(currentOffset + kCDENameLen) & 0xffff;
    int extraLen = directoryMap.getShort(currentOffset + kCDEExtraLen) & 0xffff;
    int commentLen = directoryMap.getShort(currentOffset

代码示例来源:origin: prestodb/presto

public static Slice mapFileReadOnly(File file)
      throws IOException
  {
    requireNonNull(file, "file is null");

    if (!file.exists()) {
      throw new FileNotFoundException(file.toString());
    }

    try (RandomAccessFile randomAccessFile = new RandomAccessFile(file, "r");
        FileChannel channel = randomAccessFile.getChannel()) {
      MappedByteBuffer byteBuffer = channel.map(MapMode.READ_ONLY, 0, file.length());
      return wrappedBuffer(byteBuffer);
    }
  }
}

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

raf = new RandomAccessFile(file, "r");
 channel = raf.getChannel();
 return channel.map(FileChannel.MapMode.READ_ONLY, 0, fileLength).load();
} finally {
 if (channel != null) {
  try {
   channel.close();
  } catch (IOException e) {
   raf.close();
  } catch (IOException e) {

代码示例来源:origin: Codecademy/EventHub

public static MappedByteBuffer expandBuffer(String filename, MappedByteBuffer buffer,
  long newSize) {
 buffer.force();
 int oldPosition = buffer.position();
 try (RandomAccessFile raf = new RandomAccessFile(filename, "rw")) {
  raf.setLength(newSize);
  buffer = raf.getChannel().map(FileChannel.MapMode.READ_WRITE, 0, raf.length());
  buffer.position(oldPosition);
  return buffer;
 } catch (IOException e) {
  throw new RuntimeException(e);
 }
}

代码示例来源:origin: google/guava

private static MappedByteBuffer mapInternal(File file, MapMode mode, long size)
  throws IOException {
 checkNotNull(file);
 checkNotNull(mode);
 Closer closer = Closer.create();
 try {
  RandomAccessFile raf =
    closer.register(new RandomAccessFile(file, mode == MapMode.READ_ONLY ? "r" : "rw"));
  FileChannel channel = closer.register(raf.getChannel());
  return channel.map(mode, 0, size == -1 ? channel.size() : size);
 } catch (Throwable e) {
  throw closer.rethrow(e);
 } finally {
  closer.close();
 }
}

相关文章