Nio最简单的Chanel应用
String infile = "e:\\copy_i.txt";
String outfile = "e:\\copy_o.txt";
FileInputStream fin = new FileInputStream(infile);
FileOutputStream fout = new FileOutputStream(outfile);
FileChannel fcin = fin.getChannel();
FileChannel fcout = fout.getChannel();
ByteBuffer buffer = ByteBuffer.allocate(1024);
while (true) {
buffer.clear();
int r = fcin.read(buffer); (从in流中读入到缓存区中)
if (r == -1) {
break;
}
buffer.flip(); (flip方法把limit值=position值,position值=0,用来反向写出)
fcout.write(buffer); (从缓存区中写出到out流中)
}
-----------------------------------------------------------
InetSocketAddress socketAddress = new InetSocketAddress("www.baidu.com", 80);
SocketChannel channel = SocketChannel.open(socketAddress);
channel.write(charset.encode("GET " + "/ HTTP/1.1" + "\r\n\r\n"));
ByteBuffer buffer = ByteBuffer.allocate(1024);
while (channel.read(buffer) != -1) {
buffer.flip();
System.out.println(Charset.forName("GBK").decode(buffer));
buffer.clear();// 清空缓冲
}
channel.close();