IO flow, NIO

IO stream:

a, I refers Input (Input), O refers to the Output (Output)

B, in Java, file input and output is achieved through the flow used to communicate between programs or processes, or the peripheral device write, and files

c, a stream, there must be a source and destination, which may be an area of ​​computer memory, can also be a disk file, or even a URL on the Internet, for the flow, we do not care how the data is transmitted and only needs to input data source, you can get the data to the destination.

d, processing the data stream by unit can be divided into a byte stream and a stream of characters according to the flow of the input and output streams into

 

Byte stream: an operation unit byte binary files (audio video pictures docx like, with Notepad is generally garbled file is a stream of bytes)

Common methods:

= FileInputStream the FileInputStream null ; 
a FileOutputStream FileOutputStream = null ;
 the try {
         // input stream 
    FileInputStream = new new the FileInputStream ( "C: /Java_Tools/image/hello.jpg" );
     // output stream 
        FileOutputStream = new new a FileOutputStream ( "C: / Java_Tools / hello.jpg " ); 
    
    byte [] = CAR new new  byte [1024 ];
     int length = 0 ; 
    
    // when the read data is -1, and the end of reading 
    the while ((length = FileInputStream.read (CAR)) =! -1 ) {
        fileOutputStream.write(car,0,length);
    }
    
    //冲刷缓存
    fileOutputStream.flush();
} catch (Exception e) {
    e.printStackTrace();
}finally{
    
    if(fileInputStream!=null){
        try {
            fileInputStream.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    
    if(fileOutputStream!=null){
        try {
            fileOutputStream.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    
}    

 

Character streams: byte Unicode character is converted to have a 2-byte character stream for operating the character file (Notepad, etc.)

Common methods:

FileReader fileReader null;
FileWriter fileWriter = null;
try {
    //输入流
    fileReader = new FileReader("C:/Java_Tools/log.log");
    //输出流
        fileWriter = new FileWriter("C:/Java_Tools/image/log.log");
    
    char[] car = new char[1024];
    int length = 0;
    
    while((length=fileReader.read(car))!=-1){
        fileWriter.write(car,0,length);
    }
    fileWriter.flush();
    
} catch (Exception e) {
    e.printStackTrace();
}finally{
    
    if(fileReader!=null){
        try {
            fileReader.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    
    if(fileWriter!=null){
        try {
            fileWriter.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    
}

 

Buffered stream - the data will be retrieved from disk during replication, there is a buffer

Byte stream buffer: implemented binary bytes

Input stream: BufferedInputStream

Output stream: BufferedOutputStream

Character stream buffer: to achieve a 2-byte character file

Input stream: BufferedReader

Output stream: BufferedWriter

 

Commutations: inconsistent because the default encoding and encoding the file itself used when the program is running, so that the program reads the file or output characters may appear garbled, then you can use the file byte stream operations, and then repeat the byte stream converter into a character stream

Input stream of bytes -> character input stream: InputStreamReader

Output stream of bytes -> character output stream: OutputStreamWriter

 

NIO (NEW IO):

NIO provides multiple highly scalable non-blocking network I / O, resulting in improved efficiency, NIO there are three core components: Channel, Buffer, Selector, the former two highlights

 

Buffer: Buffer is an abstract class, the type of a variable corresponding to the Buffer object represents a buffer, ByteBuffer, CharBuffer, DoubleBuffer, FloatBufferand ShortBuffer Buffer classes are subclasses of abstract classes, wherein the most common ByteBuffer

Common methods:

A, static the ByteBuffer the allocate (int Capacity): assign a new byte buffer

public class Test {
    public static void main(String[] args) {
            ByteBuffer bytebuffer=ByteBuffer.allocate(1024);
    }
}

B, int capacity (): Returns this buffer's capacity, the capacity is substantially directly members attribute is returned.

public class Test {
    public static void main(String[] args) {
            ByteBuffer bytebuffer=ByteBuffer.allocate(1024);
            System.out.println(bytebuffer.capacity());
    }
}
//输出结果:1024

C, the ByteBuffer PUT (byte B): the type of data bytes written to the buffer current position, and position + 1, 0 from the start position

public class Test {
    public static void main(String[] args) {
            ByteBuffer bytebuffer=ByteBuffer.allocate(1024);
            byte a=3;
            bytebuffer.put(a);
    }
}

D, byte [] Array (): ByteBuffer type data into the byte array

public class Test {
    public static void main(String[] args) {
            ByteBuffer bytebuffer=ByteBuffer.allocate(1024);
            byte a=3;
            bytebuffer.put(a);
            byte[] bbuf=bytebuffer.array();
    }
}

E, int position (): returns the buffer's current position, the position substantially directly members attribute is returned.

public class Test {
    public static void main(String[] args) {
            ByteBuffer bytebuffer=ByteBuffer.allocate(1024);
            System.out.println(bytebuffer.position());
            byte a=3;
            bytebuffer.put(a);
            System.out.println(bytebuffer.position());
    }
}
//输出结果:0   1

f, Buffer flip (): flip buffer, assigning a value to limit the current position, and the position zero; this method is mainly to prevent at the last output, if the buffer is not full, then the position value assigned to the limit is the current amount of data in the buffer, with the general method hasRemaining. If the attribute is not used directly limit capacity, redundant data is output.

Source analysis:

For example:

public class Test {
    public static void main(String[] args) {
            ByteBuffer bytebuffer=ByteBuffer.allocate(1024);
            bytebuffer.position();
            byte a=3;
            bytebuffer.put(a);
            bytebuffer.position();
            bytebuffer. flip();
            bytebuffer.position();
    }
}
//输出结果:0   1   0

G, byte GET () reads the current position of the byte buffer, and then the current position +1

public class Test {
    public static void main(String[] args) {
            ByteBuffer bytebuffer=ByteBuffer.allocate(1024);
            bytebuffer.position();
            byte a=3;
            bytebuffer.put(a);
            bytebuffer.position();
            bytebuffer. flip();
            bytebuffer.position();
            bytebuffer.get();
    }
}

H, boolean hasRemaining (): tells you when to release the buffer has been reached on border buffer

Source analysis:

 

 

 For example:

public class Test {
    public static void main(String[] args) {
        ByteBuffer bytebuffer=ByteBuffer.allocate(1024);
        System.out.println(bytebuffer.position());
        byte a=3;
        bytebuffer.put(a);
        System.out.println(bytebuffer.position());
        System.out.println(bytebuffer.hasRemaining());
        bytebuffer. flip();
        bytebuffer.get();
        System.out.println(bytebuffer.position());
        System.out.println(bytebuffer.hasRemaining());
    }
}
//输出结果:0   1   true   1   false

I, Buffer Clear (): the buffer is reset to empty state. It does not change any of the data elements in the buffer, but only an upper bound value is initialized to a value of capacity, and the position is set back to 0.

Source analysis:

 

 

 For example:

public class Test {
    public static void main(String[] args) {
        ByteBuffer bytebuffer=ByteBuffer.allocate(1024);
        bytebuffer.position();
        byte a=3;
        bytebuffer.put(a);
        bytebuffer.clear();
        System.out.println(bytebuffer.get());
        System.out.println(bytebuffer.position());
        System.out.println(bytebuffer.hasRemaining());
    }
}
//输出结果:3   1   true

 

 

Channel:一个接口,该接口类型变量指向的对象代表一个数据传输通道,Channel对象是面向缓冲区的:数据总是从通道读取到缓冲区(Buffer类型对象),或从缓冲区(Buffer类型对象)写入到通道中

常用方法:

a、FileChannel:从文件中读写数据。

b、DatagramChannel:通过UDP读写网络中的数据。

c、SocketChannel:通过TCP读写网络中的数据。

d、ServerSocketChannel:可以监听新进来的TCP连接,像Web服务器那样,对每一个新进来的连接都会创建一个SocketChannel。

public class Test {
    public static void main(String[] args) {
        try {
            FileInputStream fileInputStream=new FileInputStream("C:/Java_Tools/log.log");
            FileChannel inChannel=fileInputStream.getChannel();
            
            FileOutputStream fileOutputStream=new FileOutputStream("C:/Java_Tools/image/log.log");
            FileChannel ouChannel=fileOutputStream.getChannel();
            
            ByteBuffer byteBuffer= ByteBuffer.allocate(1024);
            while(inChannel.read(byteBuffer)!=-1) {
                byteBuffer.flip();
                ouChannel.write(byteBuffer);
                byteBuffer.clear();
            }    
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

Guess you like

Origin www.cnblogs.com/yimengxianzhi/p/12419523.html