使用SeekableByteChannel从不同位置读取一个字符
import java.io.IOException; import java.nio.ByteBuffer; /** 时 代 J a v a 公 众 号 提供 **/ 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/* from nowjava.com - 时代Java*/ .get("C:/folder1/folder2/folder4", "test.txt"); ByteBuffer buffer = ByteBuffer.allocate(1); String encoding = System.getProperty("file.encoding"); try (SeekableByteChannel seekableByteChannel = (Files.newByteChannel(path, EnumSet.of(StandardOpenOption.READ)))) { seekableByteChannel.position(0); System.out.println("Reading one character from position: " + seekableByteChannel.position()); seekableByteChannel.read(buffer); buffer.flip(); System.out.print(Charset.forName(encoding).decode(buffer)); buffer.rewind(); // get into the middle seekableByteChannel.position(seekableByteChannel.size() / 2); System.out.println("\nReading one character from position: " + seekableByteChannel.position()); seekableByteChannel.read(buffer); buffer.flip(); System.out.print(Charset.forName(encoding).decode(buffer)); buffer.rewind(); // get to the end seekableByteChannel.position(seekableByteChannel.size() - 1); System.o