首页  

java NIO FileChannel     所属分类 nio 浏览量 94
public interface Channel extends Closeable {
    public boolean isOpen();
    public void close() throws IOException;
}

public abstract class FileChannel extends AbstractInterruptibleChannel
    implements SeekableByteChannel, GatheringByteChannel, ScatteringByteChannel


public abstract class SelectableChannel extends AbstractInterruptibleChannel implements Channel

public abstract class AbstractSelectableChannel extends SelectableChannel

public abstract class SocketChannel extends AbstractSelectableChannel

public abstract class ServerSocketChannel extends AbstractSelectableChannel  

FileChannel
FileChannel 无法设置为非阻塞模式
只有 SelectableChannel 才能 设置为非阻塞模式 与 Selector配合使用

FileChannel 的创建

java.io.FileOutputStream.getChannel()

java.io.FileInputStream.getChannel()

java.nio.channels.FileChannel.open(Path, OpenOption...)

文件复制的两种实现方式
使用 FileChannel read write 
使用 FileChannel transferTo

注意写入文件的参数
StandardOpenOption.CREATE 
StandardOpenOption.WRITE



// copy file  use  transferTo
		
String src = file;
String dest = home + "/FileChannelTest2.txt" ;
		
FileChannel srcFileChannel = FileChannel.open(Paths.get(src));		
// StandardOpenOption CREATE 
// CREATE Create a new file if it does not exist
// CREATE_NEW Create a new file, failing if the file already exists
WritableByteChannel destFileChannel = Files.newByteChannel(Paths.get(dest),StandardOpenOption.CREATE,StandardOpenOption.WRITE);
//  java.nio.file.NoSuchFileException
srcFileChannel.transferTo(0, srcFileChannel.size(), destFileChannel);
		
srcFileChannel.close();
destFileChannel.close();
		
System.out.println("copy file  use  transferTo done");

		
// copy file  
dest = home + "/FileChannelTest3.txt" ;
srcFileChannel = FileChannel.open(Paths.get(src));
FileChannel destFileChannel2 = FileChannel.open(Paths.get(dest),StandardOpenOption.CREATE,StandardOpenOption.WRITE);		
		
ByteBuffer buffer = ByteBuffer.allocate(8);
while (srcFileChannel.read(buffer) > 0) {
// 写模式切换到读模式
buffer.flip();
while (buffer.hasRemaining()) {
    destFileChannel2.write(buffer);
}
	buffer.clear();
}
srcFileChannel.close();
destFileChannel2.close();
	
System.out.println("copy file  use  channel read and write done");


完整代码

https://gitee.com/dyyx/hellocode/blob/master/src/nio/FileChannelTest.java

上一篇     下一篇
Java NIO写事件处理技巧

java NIO buffer

Java NIO pipe

Java NIO Scatter Gather

java NIO SocketChannel

Java NIO 内存映射文件