1、通道:用于源节点与目标节点的连接,在java nio中负责缓冲区中数据的传输。Channel本身不存储数据,因此需要配合缓冲区进行传输。
2、通道的主要实现类java.nio.Channels.Channel接口: --FileChannel --SocketChannel --ServerSocketChannel --DatagramChannel
3、FileChannel通过open()方法得到通道:FileChannel inChannel = FileChannel.open(Paths.get("1.jpg"), StandardOpenOption.READ); FileChannel outChannel = FileChannel.open(Paths.get("2.jpg"), StandardOpenOption.WRITE, StandardOpenOption.READ,StandardOpenOption.CREATE_NEW);
4、获取通道的三种方式:1、java针对支持通道的类提供了getChannel()方法 本地IO: FileInputStrea罪焐芡拂m/FileOutputStream RandomAccessFile 网络IO: Socket ServerSocket DatagramSocket@Test public void test1() throws Exception{ FileInputStream fis = new FileInputStream("1.jpg"); FileOutputStream fos = new FileOutputStream("2.jpg"); FileChannel inChannel = fis.getChannel(); FileChannel outChannel = fos.getChannel(); }
5、在JDK1.7中的NIO.2针对各个通道提供了静态方法open()//使用直接缓冲辨泔矣嚣区完成文件的复制(内存映射文件) @Test public void test2() throws Exception{ FileChannel inChannel = FileChannel.open(Paths.get("1.jpg"), StandardOpenOption.READ); FileChannel outChannel = FileChannel.open(Paths.get("2.jpg"),StandardOpenOption.WRITE,StandardOpenOption.CREATE_NEW); }
6、在JDK1.7中NIO.2的Files工具类的newByteChannels@Test public void test3() throws Exception{ ByteChannel byteChannel = Files.newByteChannel(Paths.get("1.jpg"), StandardOpenOption.READ); }