通道介绍
其实通道和流还是有点相似的,但是又不完全像。
1、流只能读或者写,通道可以同时实现读写。
2、通道可以实现异步读写。
3、通道可以写缓冲区,也可以读缓冲区。
4、他们都有很多特定的子类(这个叫做工厂模式的应用)
5、
实战
将“java yyds”写到我们的java.txt文件里面
public static void main(String[] args) throws Exception{
String str = "java yyds";
FileOutputStream fos = new FileOutputStream("E:\\java.txt");
FileChannel channel = fos.getChannel();
// 创建缓冲区
ByteBuffer byteBuffer = ByteBuffer.allocate(1024);
// 放进去
byteBuffer.put(str.getBytes());
// 反转位置
byteBuffer.flip();
channel.write(byteBuffer);
fos.close();
}
ok了,家人们。
既然写了,那就再读一下。
FileInputStream fis = new FileInputStream("E:\\java.txt");
FileChannel channel = fis.getChannel();
// 创建缓冲区
ByteBuffer byteBuffer = ByteBuffer.allocate(1024);
channel.read(byteBuffer);
System.out.println(new String(byteBuffer.array()));
fis.close();
梅开二度,我现在读到了java.txt,我把它写到我们的java1.txt中。
public static void main(String[] args) throws Exception{
FileInputStream fis = new FileInputStream("E:\\java.txt");
FileOutputStream fos = new FileOutputStream("E:\\java1.txt");
FileChannel channel = fis.getChannel();
FileChannel channel1 = fos.getChannel();
// 创建缓冲区
ByteBuffer byteBuffer = ByteBuffer.allocate(1024);
// 读入缓冲区
while (true){
// 下一次清空
byteBuffer.clear();
int read = channel.read(byteBuffer);
if(read == -1){
break;
}
// 反转写进去
byteBuffer.flip();
channel1.write(byteBuffer);
}
fis.close();
fos.close();
}
我先用缓冲区读取,再写进去。
还可以拷贝文件,我现在拷贝一个java.txt
public static void main(String[] args) throws Exception{
FileInputStream fis = new FileInputStream("E:\\java.txt");
FileOutputStream fos = new FileOutputStream("E:\\java2.txt");
FileChannel channel = fis.getChannel();
FileChannel channel1 = fos.getChannel();
channel1.transferFrom(channel,0,channel.size());
fis.close();
fos.close();
}
其实读写还可以通过多Buffer完成
public static void main(String[] args) throws Exception {
ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();
InetSocketAddress inetSocketAddress = new InetSocketAddress(9999);
// 将端口绑定socket
serverSocketChannel.socket().bind(inetSocketAddress);
// 创建Buffer数组
ByteBuffer[] buffers = new ByteBuffer[3];
buffers[0] = ByteBuffer.allocate(10);
buffers[1] = ByteBuffer.allocate(10);
buffers[2] = ByteBuffer.allocate(10);
// 等待连接
SocketChannel socketChannel = serverSocketChannel.accept();
// 读取
long read = socketChannel.read(buffers);
// 反转
Arrays.asList(buffers).forEach(buffer -> buffer.flip());
socketChannel.write(buffers);
}
其实我们还可以指定读多少,写多少。但是没什么意义,就不搞了。
结束语
再见再见再见再见再见