Java.io中最核心的概念是流(Stream),面向流编程。一个流要么是输入流,要么是出入流,不能是同时是输入流也是出入流。
Java.nio中有三个核心概念:selector、channel、buffer,面向块(block)或者是面向缓冲区(buffer)编程。thread基于事件驱动从而作用在不同的channel上。buffer本身是一块内存, 底层通过数组来实现。数据的读和写都是通过buffer来实现。
通过三段示例代码来理解NIO的文件读写
public class Test1 {
public static void main(String[] args) {
IntBuffer buffer = IntBuffer.allocate(10);
for (int i = 0; i < buffer.capacity(); i ++) {
int randomNumber = new SecureRandom().nextInt(20);
buffer.put(randomNumber);
}
buffer.flip();
while (buffer.hasRemaining()) {
System.out.println(buffer.get());
}
}
}
读
public class Test2 {
public static void main(String[] args) throws IOException {
FileInputStream fileInputStream = new FileInputStream("test.txt");
FileChannel fileChannel = fileInputStream.getChannel();
ByteBuffer byteBuffer = ByteBuffer.allocate(100);
fileChannel.read(byteBuffer);
byteBuffer.flip();
while (byteBuffer.hasRemaining()) {
byte c = byteBuffer.get();
System.out.println((char) c);
}
fileChannel.close();
}
}
写
public class Test3 {
public static void main(String[] args) throws IOException {
FileOutputStream fileOutputStream = new FileOutputStream("test3.txt");
FileChannel channel = fileOutputStream.getChannel();
ByteBuffer byteBuffer = ByteBuffer.allocate(100);
byte[] bytes = "hello kitty".getBytes();
byteBuffer.put(bytes);
byteBuffer.flip();
channel.write(byteBuffer);
}
}