IO和NIO操作文件的对比

来源:互联网 发布:php object to string 编辑:程序博客网 时间:2024/04/20 01:31

原来的IO是以流的方式处理数据的,面向流的IO一次一个字节地处理数据,简单方便,但效率不高;

NIO使用块IO的处理方式,每一个操作都在一步中读取或者写出一个数据块(缓存)。

IO和NIO的对比

1.1 读取文件内容

使用IO读取指定文件前1024个字节内容

private static void ioRead(String file) throws IOException {FileInputStream in = new FileInputStream(file);byte[] b = new byte[1024];in.read(b);System.out.println(new String(b));}
使用NIO读取指定文件前1024个字节内容

private static void nioRead(String file) throws IOException {FileInputStream in = new FileInputStream(file);FileChannel channel = in.getChannel();ByteBuffer buffer = ByteBuffer.allocate(1024);channel.read(buffer);byte[] b = buffer.array();System.out.println(new String(b));}
在面向流的IO中,将数据直接写入或者将数据读到stream对象中,在NIO,所有的对象都是用缓冲区处理的,读入写入数据都放到缓冲区中,任何时候访问NIO中的数据,都是将它放入缓冲区,缓冲区实际上是一个字节数组,但不仅仅是一个数组,缓冲区还提供了对数据的结构化访问,而且还可以跟踪系统的读写进程。

1.2 NIO读文件

private static void nioRead(String file) throws IOException {FileInputStream in = new FileInputStream(file);//第一步是获取通道,我们从FileInputStream获取FileChannel channel = in.getChannel();//第二部  创建缓冲区ByteBuffer buffer = ByteBuffer.allocate(1024);//最后需要将数据从通道读取到缓冲区channel.read(buffer);byte[] b = buffer.array();System.out.println(new String(b));}

1.3 NIO写文件

private static void NIOWrite(String file) throws IOException {FileOutputStream out = new FileOutputStream(file);//第一步是获取通道,我们从FileInputStream获取FileChannel channel = out.getChannel();//第二部  创建缓冲区,并在缓冲区中存入数据ByteBuffer buffer = ByteBuffer.allocate(1024);buffer.put("测试NIO".getBytes());buffer.flip();//最后写入缓冲区channel.write(buffer);}

1.4 文件内容拷贝

private static void NIOCopy(String file) throws IOException {FileOutputStream out = new FileOutputStream(file);FileInputStream in = new FileInputStream(file);//获取输入和输出通道FileChannel outChannel = out.getChannel();FileChannel inChannel = in.getChannel();//创建缓冲区ByteBuffer buffer = ByteBuffer.allocate(1024);while(true){//clear 方法重设缓冲区,使它可以接收读入的数据buffer.clear();//从输入通道将数据读到缓冲区int r = inChannel.read(buffer);//read 方法,返回读取的字节数,可能为零,如果该通道已经到达流的末尾,则返回-1if(r == -1){break;}//flip 方法,让缓冲区可以将新读入的数据,写入到另一个通道中buffer.flip();//从输出通道中将数据写入缓冲区outChannel.write(buffer);}}


原创粉丝点击