集册 Java实例教程 使用SeekableByteChannel用截断功能替换文件部分

使用SeekableByteChannel用截断功能替换文件部分

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

600
使用SeekableByteChannel用截断功能替换文件部分

import java.io.IOException;

import java.nio.ByteBuffer;

import java.nio.channels.SeekableByteChannel;/*时 代 J a v a - nowjava.com*/

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/folder2/folder4", "test.txt");

    ByteBuffer buffer = ByteBuffer.wrap("this is a test.".getBytes());

    try (SeekableByteChannel seekableByteChannel = (Files.newByteChannel(path,

        EnumSet.of(StandardOpenOption.READ, StandardOpenOption.WRITE)))) {
        /**
        时 代 J a v a 提供 
        **/

      seekableByteChannel.truncate(200);

      seekableByteChannel.position(seekableByteChannel.size() - 1);

    
展开阅读全文