java8 AIO AsynchronousFileChannel例

package com.kd.nio;
 
import java.nio.ByteBuffer;
import java.nio.channels.AsynchronousFileChannel;
import java.nio.channels.CompletionHandler;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;
import java.util.concurrent.Future;
 
 
public class AsynchronousFileChannelTest {
	public static ByteBuffer read()throws Exception{
		Path path = Paths.get("f:","test1.txt");
  		AsynchronousFileChannel afc = AsynchronousFileChannel.open(path , StandardOpenOption.READ) ;
  		ByteBuffer byteBuffer = ByteBuffer.allocate(1024);
  		
  		
  		Future<Integer> read = afc.read(byteBuffer, 0);
  		
  		while(!read.isDone()){
  			System.out.println("reading");
  		}
  		System.out.println(read.isDone());
  		
  		System.out.println(byteBuffer);
  		afc.close();
  		return byteBuffer;
	}
	
	public static void read2()throws Exception{
		Path path = Paths.get("f:","test1.txt");
  		AsynchronousFileChannel afc = AsynchronousFileChannel.open(path , StandardOpenOption.READ) ;
  		ByteBuffer byteBuffer = ByteBuffer.allocate(1024);
  		
  		
  		 afc.read(byteBuffer, 0, "at", new CompletionHandler<Integer,Object>(){
 
			@Override
			public void completed(Integer result, Object attachment) {
				System.out.println(attachment+"/"+result);
				System.out.println(byteBuffer);
				try {
					write2(byteBuffer);
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
 
			@Override
			public void failed(Throwable exc, Object attachment) {
				
			}
  			 
  		 });
  		
  		Thread.sleep(5000);
  		System.out.println("close");
  		afc.close();
	}
	
	public static void write(ByteBuffer byteBuffer)throws Exception{
		Path path = Paths.get("f:","test.txt");
  		AsynchronousFileChannel afc = AsynchronousFileChannel.open(path , StandardOpenOption.CREATE,StandardOpenOption.WRITE) ;
  		byteBuffer.flip();
  		Future<Integer> write = afc.write(byteBuffer, 0);
  		while(!write.isDone()){
  			System.out.println("writing");
  		}
  		System.out.println(write.isDone());
  		System.out.println(byteBuffer);
  		afc.close();
	}
	
	public static void write2(ByteBuffer byteBuffer)throws Exception{
		Path path = Paths.get("f:","test.txt");
  		AsynchronousFileChannel afc = AsynchronousFileChannel.open(path , StandardOpenOption.CREATE,StandardOpenOption.WRITE) ;
  		byteBuffer.flip();
  		afc.write(byteBuffer, 0, "attachment",  new CompletionHandler<Integer,Object>(){
 
			@Override
			public void completed(Integer result, Object attachment) {
				System.out.println(result+"/"+attachment);
				System.out.println(byteBuffer);
			}
 
			@Override
			public void failed(Throwable exc, Object attachment) {
				System.out.println(byteBuffer);
			}
  			
  		});
  		
  		Thread.sleep(5000);
  		System.out.println("close");
  		afc.close();
  	
  		
	}
     
      public static void main(String[] args) throws Exception{
    	
    	 read2();
  		
	}
	
 
}

猜你喜欢

转载自blog.csdn.net/yiyihuazi/article/details/107838324