集册 Java实例教程 使用SeekableByteChannel接口随机访问文件

使用SeekableByteChannel接口随机访问文件

欢马劈雪     最近更新时间:2020-01-02 10:19:05

489
StandardOpenOption枚举常量定义以下值。
/** 来自 时 代 J a v a - N o w J a v a . c o m**/

import java.io.IOException;

import java.nio.ByteBuffer;

import java.nio.channels.SeekableByteChannel;

import java.nio.charset.Charset;

import java.nio.file.Files;

import java.nio.file.Path;

import java.nio.file.Paths;

import java.nio.file.StandardOpenOption;

import java.util.EnumSet;


public class Main {

  public static void main(String[] args) {

    Path path = Paths.get("C:/folder1/folder0/folder8", "story.txt");/* 来 自 时代Java - N o w  J a v a . c o m*/

    try (SeekableByteChannel seekableByteChannel = Files.newByteChannel(path,

        EnumSet.of(StandardOpenOption.READ))) {


      ByteBuffer buffer = ByteBuffer.allocate(12);

      String encoding = System.getProperty("file.encoding");

      buffer.clear();


      while (seekableByteChannel.read(buffer) &g
展开阅读全文