Java传统IO流和NIO流的简单对比介绍

通过对文件的拷贝来对比传统IO流和NIO流

将底层流封装成处理流以后进行分段读取。

/*将本身源代码拷贝到TXT文件*/
public class TraditionIO {
    public static void main(String[] args) {
        try(BufferedReader br = new BufferedReader(new FileReader("src/com/ming/test/TraditionIO.java")); //准备输入输出"处理"流
            BufferedWriter bw = new BufferedWriter(new FileWriter("TEMP.txt"))){
            //缓存数组
            char temp[] = new char[1024];
            int receive = 0;
            while((receive = br.read(temp)) > 0){
                bw.write(temp,0,receive);   //分段读取
            }
        }catch (Exception e){
            e.printStackTrace();
        }
    }
}

直接通过InputStream/OutputStream获取Channel,Channel和Buffer进行配合进行拷贝。

public class NIO {
    public static void main(String[] args) {
        try(FileChannel inFc = (new FileInputStream("src/com/ming/test/NIO.java").getChannel());    //通过节点流来获取管道
            FileChannel outFc = (new FileOutputStream("TEMP2.txt")).getChannel()) {
            //通过管道获取Buffer,并将源文件数据全部"塞进"Buffer
            MappedByteBuffer mbb = inFc.map(FileChannel.MapMode.READ_ONLY,0,new File("src/com/ming/test/NIO.java").length());
            //将Buffer里面的数据取出
            outFc.write(mbb);
        }catch (Exception e){
            e.printStackTrace();
        }
    }
}

NIO的性能比传统IO的要高,使用也更方便。

public class NIO {
    /*public static void main(String[] args) {
        try(FileChannel inFc = (new FileInputStream("src/com/ming/test/NIO.java").getChannel());    //通过节点流来获取管道
            FileChannel outFc = (new FileOutputStream("TEMP2.txt")).getChannel()) {
            //通过管道获取Buffer,并将源文件数据全部"塞进"Buffer
            MappedByteBuffer mbb = inFc.map(FileChannel.MapMode.READ_ONLY,0,new File("src/com/ming/test/NIO.java").length());
            //将Buffer里面的数据取出
            outFc.write(mbb);
        }catch (Exception e){
            e.printStackTrace();
        }
    }*/
    public static void main(String[] args) {
        //如果习惯了传统IO的分段读取或者担心Channel对应的文件过大,使用map()方法一次将所有的文件内容映射到内存中引起性能下降,也可以使用Channel和Buffer传统的分段读取
        try(FileChannel inFc = (new FileInputStream("src/com/ming/test/NIO.java")).getChannel();){  //通过节点流获取管道
            //定义Buffer,相当于传统IO流中的byte[]
            ByteBuffer bb = ByteBuffer.allocate(64);    //手动定义Buffer,而不是通过管道映射出一个Buffer
            while(inFc.read(bb) > 0){   //程序不能直接从Channel中读取数据,必须通过Buffer作为中间变量,就想传统的IO流一样,必须先从输入流中
                                        //读取数据到一个字节数组,然后将字节数组里面的数据写入到输出源
                bb.flip();  //为读取数据做准备
                System.out.print(new String(bb.array()));
                bb.clear();

            }
        }catch (Exception e){
            e.printStackTrace();
        }
    }
}
原文地址:https://www.cnblogs.com/chiweiming/p/11882828.html