通过对文件的拷贝来对比传统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的要高,使用也更方便。

12-30 03:46