一、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-hao12

最低0.47元/天 解锁文章
940





