使用文件锁定写入文件
import java.nio.ByteBuffer; import java.nio.channels.AsynchronousFileChannel; import java.nio.channels.FileLock; import java.nio.file.Path;//来自 时 代 Java 公 众 号 - nowjava.com import java.nio.file.Paths; import java.nio.file.StandardOpenOption; import java.util.concurrent.Future; public class Main { public static void main(String[] args) { ByteBuffer buffer = ByteBuffer.wrap("this is a test.".getBytes()); Path path = Paths.get("C:/folder1/", "test.txt"); try (AsynchronousFileChannel asynchronousFileChannel = AsynchronousFileChannel/*时代Java公众号 - nowjava.com 提 供*/ .open(path, StandardOpenOption.WRITE)) { Future<FileLock> featureLock = asynchronousFileChannel.lock(); System.out.println("Waiting for the file to be locked ..."); FileLock lock = featureLock.get(); // FileLock lock = asynchronousFileChannel.lock().get(); if (lock.isValid()) { Future<Integer> featureWrite = asynchronousFileChannel.write(buffer, 0); System.out.println("Waiting for the bytes to be written ..."); int written = featureWrite.get();