使用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);