- Channel只能和Buffer进行数据沟通,程序不能访问Channel中的数据,包括写入,读出都不行
- 所有的Channel都不应该通过构造器来直接创建,要通过传统的结点流的getChannel方法来返回对应的Channel
- 具体的讲解穿插在代码之中
import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.nio.CharBuffer; import java.nio.MappedByteBuffer; import java.nio.channels.FileChannel; import java.nio.charset.Charset; import java.nio.charset.CharsetDecoder; public class FileChannelTest { public static void main(String args[]){ File f = new File("src/FileChannelTest.java"); try( // 以下两句说明FileChannel对象不能通过构造器构造,要通过输入输出流来获得 FileChannel inChannel = new FileInputStream(f).getChannel(); FileChannel outChannel = new FileOutputStream("a.txt").getChannel()) { MappedByteBuffer buffer = inChannel.map(FileChannel.MapMode.READ_ONLY,0,f.length()); // 这一句是将FileChannel中的全部数据映射到Buffer中 Charset charset = Charset.forName("GBK"); // 使用GBK的字符集来创建解码器 outChannel.write(buffer); // 直接将buffer中内容写出 buffer.clear(); // clear的方法在前面有介绍过 CharsetDecoder decoder = charset.newDecoder(); // 实例化解码器对象 CharBuffer charBuffer = decoder.decode(buffer); // 解码 System.out.println(charBuffer); }catch (IOException e){ e.printStackTrace(); } } }
java输入输出(12)Channel
猜你喜欢
转载自blog.csdn.net/weixin_39452731/article/details/82631530
今日推荐
周排行