【摘要】 一、NIO在文件读写方面相对于传统IO来说,性能高很多 /** * 文件读写的NIO * @param args * @throws IOException */ public static void main(String[] args) throws IOException {
//1.NIO采用通道+缓存区使得新式的IO操作直接面向缓存区,并且是非阻塞的
//2….
一、NIO在文件读写方面相对于传统IO来说,性能高很多
/**
* 文件读写的NIO
* @param args
* @throws IOException
*/
public static void main(String[] args) throws IOException {
//1.NIO采用通道+缓存区使得新式的IO操作直接面向缓存区,并且是非阻塞的
//2.Channel是支持读写双向操作,基于RandomAccessFile实现的
RandomAccessFile file =new RandomAccessFile(“C:\\Users\\hejie\\Downloads\\hao123.txt”, “r”);
FileChannel channel = file.getChannel();
ByteBuffer buffer = ByteBuffer.allocate((int)file.length());
//3.利用RandomAccessFile的读指针
channel.read(buffer);
//4.切换缓存区为读模式
buffer.flip();
byte[] res = new byte[(int)file.length()];
buffer.get(res,0, buffer.limit());
System.out.println(new String(res));
RandomAccessFile file2 =new RandomAccessFile(“C:\\Users\\hejie\\Downloads\\new-hao1234.txt”, “rw”);
FileChannel channel2 = file2.getChannel();
ByteBuffer buffer2 = ByteBuffer.allocate((int)file.length());
ByteBuffer src = buffer2.put(res,0, buffer.limit());
//5.切换缓存区为写模式
buffer2.flip();
//6.利用RandomAccessFile的写指针
channel2.write(src);
channel.close();
channel2.close();
}
二、NIO在网络通信方面的表现
文章来源: blog.csdn.net,作者:coderyqwh,版权归原作者所有,如需转载,请联系作者。
原文链接:blog.csdn.net/coderyqwh/article/details/116758501