JAVA NIO——Buffer和FileChannel

 

 

 

 

 

Java NIO和IO的主要区别

IO NIO
面向流 面向缓冲
阻塞IO 非阻塞IO
选择器

 

示例:

 1 import java.io.FileInputStream;
 2 import java.io.FileOutputStream;
 3 import java.io.IOException;
 4 import java.io.UnsupportedEncodingException;
 5 import java.nio.ByteBuffer;
 6 import java.nio.channels.FileChannel;
 7 import java.nio.charset.Charset;
 8 
 9 public class BufferToText {
10 
11     public static void main(String[] args) {
12         try {
13             //--以系统默认编码方式写文件
14             FileChannel fc = new FileOutputStream("data2.txt").getChannel();
15             fc.write(ByteBuffer.wrap("测试字符".getBytes()));
16             fc.close();
17 
18             //--读文本
19             fc = new FileInputStream("data2.txt").getChannel();
20             ByteBuffer buff = ByteBuffer.allocate(1024);
21             fc.read(buff);
22             buff.flip();
23             //显示乱码,采用默认的编码方式(UTF-16BE)将ByteBuffer转换成CharBuffer
24             System.out.println(buff.asCharBuffer());
25             buff.rewind();//准备重读
26 
27             //当前系统默认编码方式
28             String encoding = System.getProperty("file.encoding");
29             //下面我们使用系统默认的编码方式(GBK)将ByteBuffer转换成CharBuffer
30             System.out.println("Decoded using " + encoding + ": "
31                     + Charset.forName(encoding).decode(buff));//显示正常,因为写入与读出时采用相同编码方式
32 
33             //--或者,先以UTF-16BE编码后再写文件
34             fc = new FileOutputStream("data2.txt").getChannel();
35             fc.write(ByteBuffer.wrap("测试字符".getBytes("UTF-16BE")));
36             fc.close();
37             // 再尝试读
38             fc = new FileInputStream("data2.txt").getChannel();
39             buff.clear();
40             fc.read(buff);
41             buff.flip();
42             //显示正常,可见asCharBuffer()方式是以UTF-16BE解码的
43             System.out.println(buff.asCharBuffer());
44 
45             //--也可直接通过CharBuffer写也是可以的
46             fc = new FileOutputStream("data2.txt").getChannel();
47             buff = ByteBuffer.allocate(8);//UTF-16编码时每个字符占二字节,所以需四个
48             //将ByteBuffer转换成CharBuffer后再写
49             buff.asCharBuffer().put("测试字符");
50             fc.write(buff);
51             fc.close();
52             //读显示
53             fc = new FileInputStream("data2.txt").getChannel();
54             buff.clear();
55             fc.read(buff);
56             buff.flip();
57             //同时也采用默认的转换方式asCharBuffer将ByteBuffer转换成CharBuffer
58             System.out.println(buff.asCharBuffer());//显示正常
59         } catch (UnsupportedEncodingException e) {
60             e.printStackTrace();
61         } catch (IOException e) {
62             e.printStackTrace();
63         }
64     }
65 }

 

 

 

 

 

 

 

 

 

posted @ 2016-08-26 10:47  风雪夜归人shen  阅读(648)  评论(0编辑  收藏  举报