java NIO 面向通道 缓存区 IO 面向流的
通道是双向的可读可写 流是单向的只能读或只能写
NIO 非阻塞的 可以设置成异步的 IO 只能是同步阻塞的
NIO 读写基本用法
package com.bowei.nio;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.charset.Charset;
/**
* @Description:
* @Auther:
* @Date: 2019/12/25 10:42
* @version:
*/
public class NioReadWriteDemo {
private static String pathName = "d://read.txt";
private static String fileName = "d://write.txt";
public static void read() throws Exception {
FileInputStream inputStream = new FileInputStream(new File(pathName));
// 通过FileInputStream 获取FileChannel 文件类型的通道
FileChannel channel = inputStream.getChannel();
// 指定缓存区的大小
ByteBuffer byteBuffer = ByteBuffer.allocate(1024);
System.out.println("限制是" + byteBuffer.limit() + "容量大小是" + byteBuffer.capacity());
int len;
while ((len = channel.read(byteBuffer)) != -1) {
// 读取后 将位置设为0 将limit设置为容量,以备下次读数据的时候从0开始存储
byteBuffer.clear();
byte[] array = byteBuffer.array();
System.out.println("start..............");
String str = new String(array, 0, len);
System.out.println(str);
System.out.println("end..................");
System.out.println("限制是" + byteBuffer.limit() + "容量是" + byteBuffer.capacity() + "位置是" + byteBuffer.position());
}
channel.close();
inputStream.close();
}
public static void write() throws Exception {
FileOutputStream outputStream = new FileOutputStream(new File(fileName));
FileChannel channel = outputStream.getChannel();
ByteBuffer byteBuffer = Charset.forName("UTF-8").encode("你好吗你好吗你好吗你好吗你好吗你好吗你好吗");
System.out.println("limit===" + byteBuffer.limit() + "容量==" + byteBuffer.capacity() + "position===" + byteBuffer.position());
int len;
while ((len = channel.write(byteBuffer)) != 0) {
// 这里不需要clear 将缓冲区的数据写到管道后 第二次接着上一次写入的数据继续写
System.out.println("写入的长度" + len);
}
channel.close();
outputStream.close();
}
public static void readAndWrite() throws Exception {
FileInputStream fileInputStream = new FileInputStream(new File(pathName));
FileOutputStream fileOutputStream = new FileOutputStream(new File(fileName));
FileChannel channel = fileInputStream.getChannel();
FileChannel outChannel = fileOutputStream.getChannel();
ByteBuffer bf = ByteBuffer.allocate(1024);
System.out.println("限制是:" + bf.limit() + "容量是:" + bf.capacity() + "位置是:" + bf.position());
int length = -1;
while ((length = channel.read(bf)) != -1) {
//buffer 的读写转换 必须调用这个方法
bf.flip();
int outLenth = 0;
while ((outLenth = outChannel.write(bf)) != 0) {
System.out.println("读" + length + "写" + outLenth);
}
// 读完之后必须要做的方法
bf.clear();
}
channel.close();
fileInputStream.close();
fileOutputStream.close();
}
public static void main(String[] args) throws Exception {
// read();
// write();
readAndWrite();
}
}