NIO读写文件

来源:互联网 发布:阿里云域名无法使用 编辑:程序博客网 时间:2024/05/22 17:15

读取数据:

    /**     *          * @discription NIO读取文件         * @author XuJD                * @created 2017年6月29日 下午6:05:48              * @throws IOException     */    public void B() throws IOException{         Charset charset = Charset.forName("GBK");// 创建GBK字符集,防止乱码         CharsetDecoder decoder = charset.newDecoder();         //获取文件        FileInputStream fileInputStream = new FileInputStream("G:\\test.txt");        //获取通道        FileChannel fileChannel = fileInputStream.getChannel();        //创建缓冲区,指定大小        ByteBuffer byteBuffer = ByteBuffer.allocate(102400);        CharBuffer charBuffer = CharBuffer.allocate(102400);          //读取数据到缓冲区         int count =fileChannel.read(byteBuffer);         while(count!=-1){             System.out.println("count = "+count);                byteBuffer.flip();             decoder.decode(byteBuffer, charBuffer, false);               charBuffer.flip();               while(charBuffer.hasRemaining()){                 System.out.print(charBuffer.get());             }             System.out.println();//换行             byteBuffer.clear();             charBuffer.clear();            count = fileChannel.read(byteBuffer);          }         fileChannel.close();         fileInputStream.close();    }

写入数据:

    /**     *          * @discription NIO写入数据         * @author XuJD                * @created 2017年6月29日 下午6:06:16              * @throws IOException     */    @Test    public void c() throws IOException{        String a="AAAvvv";        //获取文件        FileOutputStream fout = new FileOutputStream( "g:\\test.txt",true); //true表示在末尾追加,不然直接覆盖        //获取通道        FileChannel fc = fout.getChannel();          //创建缓冲区        ByteBuffer buffer = ByteBuffer.allocate( 1024 );         buffer.put(a.getBytes());          buffer.flip();          fc.write( buffer );          fout.close();     }