集册 Java实例教程 文件写入以及Future和AsynchronousFileChannel

文件写入以及Future和AsynchronousFileChannel

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

435
文件写入以及Future和AsynchronousFileChannel

import java.nio.ByteBuffer;

import java.nio.channels.AsynchronousFileChannel;/*来自 nowjava.com - 时代Java*/

import java.nio.file.Path;

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/", "story.txt");

    try (AsynchronousFileChannel asynchronousFileChannel = AsynchronousFileChannel

        .open(path, StandardOpenOption.WRITE)) {

      Future<Integer> result = asynchronousFileChannel.write(buffer, 100);

      while (!result.isDone()) {

        System.out.println("Do something else while writing ...");/*n o w  j a v a  . c o m 提 供*/

      }

      System.out.println(
展开阅读全文