童无心 2016-11-11 07:22 采纳率: 0%
浏览 1534

nio文本文件读写的问题

读文本文件,第二次是乱码,猜测问题是 bytebuffer 读取的数据不全,怎么解决×

 FileInputStream in = new FileInputStream("E:/eula.2052.txt");
        FileChannel channel = in.getChannel();
        ByteBuffer buf = ByteBuffer.allocate(1024);

        int len = -1;
        while((len = channel.read(buf)) != -1){
            buf.flip();
            System.out.println(Arrays.toString(buf.array()));
            //System.out.println(len+":"+buf.limit()+":"+buf.capacity()+":"+buf.position()+":"+buf);
            byte[] byt=new byte[len];
            Charset cs = Charset.forName ("Unicode");
            buf.get(byt,buf.position(),len);   
            String news = new String(byt, cs);
            System.out.println(Arrays.toString(news.getBytes("Unicode")));


            System.out.println("-------------------------------------------------------------");
            buf.compact();
        }
        in.close();







  • 写回答

0条回答 默认 最新

    报告相同问题?