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