java异步读取文件2种实现
`import com.sun.tools.jconsole.JConsoleContext;
import java.io.;
import java.lang.reflect.Array;
import java.math.BigDecimal;
import java.nio.ByteBuffer;
import java.nio.channels.AsynchronousFileChannel;
import java.nio.channels.CompletionHandler;
import java.nio.channels.FileChannel;
import java.nio.channels.FileLock;
import java.nio.file.OpenOption;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;
import java.time.LocalDate;
import java.util.;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;
import java.util.stream.Collectors;
import java.util.stream.Stream;
public class Main {
public static void main(String[] args) throws IOException, ExecutionException, InterruptedException {
/基于Future接口的异步读取文件/
// AsynchronousFileChannel channel = AsynchronousFileChannel.open(Paths.get("G:\C#图解教程(第四版高清).pdf"), StandardOpenOption.READ);
// ByteBuffer buffer = ByteBuffer.allocateDirect(13010241024);
// var result = channel.read(buffer,0);
// while(!result.isDone())
// {
// System.out.printf("我还没完成呢,宝贝!");
// }
// buffer.flip();//将缓存字节数组的指针设置为数组的开始下标0,否则读的就是最后一个位置byte = 0
// byte[] data = new byte[buffer.limit()];
// buffer.get(data);
// //System.out.println(data.toString());
// buffer.clear();
/*基于回调的读取文件*/
var fc = new CompletionHandler<Integer,Object>(){
@Override
public void completed(Integer result, Object attachment) {
System.out.println("我完成了"+result);
}
@Override
public void failed(Throwable exc, Object attachment) {
System.out.println("我出了点问题!" +exc.getMessage());
}
};
ByteBuffer buffer = ByteBuffer.allocateDirect(130*1024*1024);
try (AsynchronousFileChannel channel = AsynchronousFileChannel.open(Paths.get("G:\\C#图解教程(第四版高清).pdf"),StandardOpenOption.READ,StandardOpenOption.WRITE)){
channel.write(buffer,0,null ,fc);
Thread.sleep(1000);
}
}
}
`