FileChannel
ByteBuffer唯一直接与通道交互的缓冲器。FileInputStream,FileOutputStream,RandomAccessFile能够产生FileChannel。Reader和Writer不能产生Channel。但是java.nio.channels.Channels类提供了实用方法,可以在通道中产生Reader和Writer。
package com.zachary.io.nio;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
/**
* @author Zachary.Zheng
* @version 1.0
* @date 2020年5月30日 下午5:01:34
*/
public class GetChannel {
private static final int BSIZE = 1024;
public static void main(String[] args) throws IOException {
File file = new File("file/output/nio");
file.mkdirs();
FileChannel fc = new FileOutputStream("file/output/nio/data.txt").getChannel();
fc.write(ByteBuffer.wrap("Some text ".getBytes()));
fc.close();
fc = new RandomAccessFile("file/output/nio/data.txt", "rw").getChannel();
fc.position(fc.size()); // 移动到最后
fc.write(ByteBuffer.wrap("Some more ".getBytes()));
fc.close();
fc = new FileInputStream("file/output/nio/data.txt").getChannel();
ByteBuffer buff = ByteBuffer.allocate(BSIZE); // 设置缓冲器大小
fc.read(buff); // 告知FileChannel向ByteBuffer存储字节
buff.flip(); // 让缓冲器做好让别人读取字节的准备
while (buff.hasRemaining()) {
System.out.print((char) buff.get());
}
}
}
使用FileChannel复制文件
ByteBuffer.allocate 设置缓冲器大小
FileChannel的read()方法讲字节存储到缓冲器中。ByteBuffer.flip()方法,让缓冲器做好让别人读取的准备。ByteBuffer.clear()重新安排内部指针,为下一次read()做准备。
package com.zachary.io.nio;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
/**
* @author Zachary.Zheng
* @version 1.0
* @date 2020年5月30日 下午5:20:28
*/
public class ChannelCopy {
private static final int BSIZE = 1024;
public static void main(String[] args) throws IOException {
FileChannel in = new FileInputStream("file/output/nio/copySource.txt").getChannel();
FileChannel out = new FileOutputStream("file/output/nio/copyDest.txt").getChannel();
ByteBuffer buff = ByteBuffer.allocate(BSIZE);
while (in.read(buff) != -1) {
buff.flip();
out.write(buff);
buff.clear();
}
}
}
直接相连
package com.zachary.io.nio;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.channels.FileChannel;
/**
* @author Zachary.Zheng
* @version 1.0
* @date 2020年5月30日 下午5:33:05
*/
public class TransferTo {
public static void main(String[] args) throws IOException {
FileChannel in = new FileInputStream("file/output/nio/copySource.txt").getChannel();
FileChannel out = new FileOutputStream("file/output/nio/copyDirectDest.txt").getChannel();
in.transferTo(0, in.size(), out);
/**
* OR:
* Out.transferFrom(in, 0, in.size());
*/
}
}