It refers to a new new Java NIO IO, opposite the OIO, also known as non-blocking IO, IO multiplexer corresponding to the four basic types of IO, the core has three main components, Channel (pipe), Buffer (buffer) selector (selector)
See IO channel equivalent to the traditional collection of input and output stream, both readable and writable, there are four categories,
FileChannel write data, the file path for the file
SocketChannel channel socket for a data read TCP connection socket socket,
A ServerSocketChannel, server socket channel, allowing listening TCP connection request, listen to each request, to create a secure channel socket SocketChannel
DatagramChanne datagram channel (UDP protocol read data)
1.fileChannel practice
package com.example.demo; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.nio.ByteBuffer; import java.nio.channels.FileChannel; /** * Created by Administrator on 2019/9/22. */ public class NioChannelTest { public static void main(String[] args) { fileChannelCopyFile(); } public static void fileChannelCopyFile(){ File srcFile=new File("srcFile.txt"); File destFile=new File("destFile.txt"); try{ if(!destFile.exists()) destFile.createNewFile(); }catch(Exception e){} FileInputStream fis=null; FileOutputStream fos=null; FileChannel inChannel=null; FileChannel outChannel=null; try{ fis=new FileInputStream(srcFile); fos=new FileOutputStream(destFile);
//通道的获取 inChannel=fis.getChannel(); outChannel=fos.getChannel(); int length=-1; ByteBuffer buf=ByteBuffer.allocate(1024); while((length=inChannel.read(buf))!=-1){ buf.flip(); int outlength=0; //将buf写入到输出通道 while((outlength=outChannel.write(buf))!=0){ System.out.println("the byte-len of being wrote"+outChannel); } //Switching to the write mode, the empty buf buf.clear (); } // mandatory flushed to disk outChannel.force ( to true ); } the catch (Exception E) {} the finally { the try {// close the passage outChannel.close () ; fos.close (); inChannel.close (); fis.close (); } the catch (Exception E) {} } } }
输出:the byte-len of being wrote==29
result