java之nio(3)
通道(Channel)


channel边读边写
package nio;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
public class ChannelTest {
public static void main(String[] args) throws Exception{
ByteBuffer buffer = ByteBuffer.allocate(10);//开辟10个缓冲区
//读文件
FileInputStream in = new FileInputStream("F:\\1.txt");
FileChannel inChannel = in.getChannel();
//写文件
FileOutputStream out = new FileOutputStream("F:\\2.txt");
FileChannel outChannel = out.getChannel();
String str = "12345";//初始化信息
buffer.put(str.getBytes());//把初始化信息放入缓冲区
int temp = 0;
while((temp=inChannel.read(buffer))!=-1) {//如果还有多余的缓冲区则继续读取直到缓冲区满
buffer.flip();//每次缓冲区重置(通过改变position=0),必须把内容展示出来
outChannel.write(buffer);//写入通道
buffer.clear();//每次必须清空缓冲区,否则while循环每次 read读取的时候的缓冲区已满,read不会再读取新内容,陷入死循环
}
inChannel.close();
in.close();
outChannel.close();
out.close();
}
private static void printInfo(ByteBuffer buffer) {
while(buffer.hasRemaining()) {
System.out.print((char)buffer.get()+"、");
}
System.out.println();
}
}
MappedByteBuffer(内存映射流)



代码:
package nio;
import java.io.FileInputStream;
import java.nio.ByteBuffer;
import java.nio.MappedByteBuffer;
import java.nio.channels.FileChannel;
public class MappedByteBufferTest {
public static void main(String[] args) throws Exception{
//读文件
FileInputStream in = new FileInputStream("F:\\1.txt");
FileChannel inChannel = in.getChannel();
//开辟内存通道,只读模式,大小为文件大小,MappedByteBuffer只为MapMode.READ_ONLY,如果要操作写模式太危险
MappedByteBuffer mappedByteBuffer = inChannel.map(FileChannel.MapMode.READ_ONLY, 0, in.available());
printInfo(mappedByteBuffer);
inChannel.close();
in.close();
}
private static void printInfo(ByteBuffer buffer) {
while(buffer.hasRemaining()) {
System.out.print((char)buffer.get()+"、");
}
System.out.println();
}
}