集册 Java实例教程 使用SeekableByteChannel查询位置

使用SeekableByteChannel查询位置

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

436
使用SeekableByteChannel查询位置

import java.io.IOException;

import java.nio.ByteBuffer;

import java.nio.channels.SeekableByteChannel;

import java.nio.file.Files;// 来自 nowjava.com

import java.nio.file.Path;

import java.nio.file.Paths;

import java.nio.file.StandardOpenOption;


public class Main {


  public static void main(String[] args) throws IOException {

    int bufferSize = 8;

    Path path = Paths.get("/home/docs/users.txt");

    //

    final String newLine = System.getProperty("line.separator");

    try (SeekableByteChannel sbc = Files.newByteChannel(path, StandardOpenOption.WRITE)) {

      ByteBuffer buffer;

      long position = sbc.size();

      sbc.position(position);// 来自 N o  w  J a v a . c o m - 时  代  Java

      System.out.println("Position: " + sbc.position());


      buffer = ByteBuffer.wrap((newLine + "Paul").getBytes());

      sbc.write(buffer);

      System.out.println("Position: " + sbc.position());

      buffer = ByteBuffer.wrap((newLine + "Carol").getBytes());

      sbc.write(buffer);

展开阅读全文