首页 > 技术文章 > Java NIO 学习笔记 读写结合补充

kuoAT 2017-06-23 11:30 原文

小练习:nio读写文件,将fileread中的内容读取到filewrite中

        try {
            //创建输入通道
            FileInputStream fis = new FileInputStream("F:/iotest/readfile.txt");
            FileChannel readChannel = fis.getChannel();
            //创建缓冲区
            ByteBuffer buffer = ByteBuffer.allocate(500);
            //创建输出通道
            FileOutputStream fos = new FileOutputStream("F:/iotest/filewrite.txt");
            FileChannel writeChannel = fos.getChannel();
            
            while (true) {
                buffer.clear();
                //将文件内容读到缓冲区中
                int mark = readChannel.read(buffer);
                if (mark==-1) {
                    break;
                }
                buffer.flip();
                writeChannel.write(buffer);
            }
            
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

代码运行前:

readfile:

 

filewrite:

代码运行后:

readfile:

 

filewrite:

 

推荐阅读