I/O issues are one of the main problems in today's Internet Web applications, as data flows everywhere in the web in this massive data age. The flow of the process involves I/O problems, it can be said that most WEB application system bottlenecks are I/O bottlenecks.
byte I/Obyte input stream InputStream
InputStream itself is an abstract class that must rely on its subclasses to use this class. If a byte stream needs to be read from a file, it is implemented using FileInputStream.
public class Fileinputstreamtest {public static void main (string[] args) throws IOException { file F = new File ("C:/te St.txt "); InputStream in=new FileInputStream (f); Byte[] b=new byte[(int) f.length ()]; In.read (b);//Read byte stream in.close (); System.out.println (New String (b));} }
Output:
Content of the Test.txt file!
byte output stream outputstream
OutputStream is also an abstract class that wants to use this class to rely on its subclasses. if a byte stream needs to be written to a file, it is implemented with FileOutputStream.
public class Fileoutputstreamtest {public static void main (string[] args) throws IOException {file F=new file ("C:/test.txt "); OutputStream out=new FileOutputStream (f); String str= "writes the contents of the file! "; byte[] B=str.getbytes (); Out.write (b);//write Byte stream Out.close ();}}
after the program executes, the contents of the Test.txt file become: "Write the contents of the file!" ”。
character I/Ocharacter input stream: Reader
Reader is an abstract class , and you must rely on its subclasses to use this class . If you want to read a stream of characters from a file now, you can use the FileReader subclass directly.
public class Filereadertest {public static void main (string[] args) throws IOException {file F=new file ("C:/test.txt"); Reader input=new FileReader (f); char[] C=new char[1024];int len=input.read (c); Input.close (); System.out.println (New String (C,0,len));} }
character output stream: Writer
Writer is an abstract class, if you want to use this class to rely on its subclasses. If you want to write a stream of characters to the file now, you can use the fileWriter subclass directly.
public class Filewritertest {public static void main (string[] args) throws IOException {file F=new file ("C:/test.txt"); Writer out=new FileWriter (f); String str= "hello! "; Out.write (str); Out.close ();}}
Byte stream and character stream
Flow Concept : In the program all the data is transmitted or saved in a stream, the program needs data to use the input stream to read data, and when the program needs to save some data, it is necessary to use the output stream to complete.
The byte Stream processing Unit is 1 bytes, manipulating bytes and byte arrays. the character Stream processing unit is a 2-byte Unicode character that operates on characters, character arrays, or strings, respectively. All of the files are stored in byte (byte) storage, and the characters that are not files on the disk are encoded into bytes, and then the bytes are stored to disk. When reading a file (especially a text file), it is also a byte-by-byte read to form a sequence of bytes.
Byte stream mainly used in processing binary data , It is processed in bytes. But in fact, a lot of data is text, and put forward the concept of character stream , it is based on the code of the virtual machine to deal with , that is, the conversion of character sets. in general, bytes are used to deal with files, while characters are used to deal with people .
In actual development, the problem of garbled characters is actually caused by the non-unification between character stream and byte stream.
conversion between bytes and characters
In addition, data persistence or network transmission is done in bytes, so there must be a conversion of characters to bytes or bytes to characters.
public class Outputstreamwritertest {public static void main (string[] args) throws IOException {file F=new file ("c:/test.t XT "); String charset= "UTF-8";//string charset= "iso-8859-1";//write String into byte stream outputstream out=new FileOutputStream (f); O Utputstreamwriter writer=new OutputStreamWriter (out,charset);//stores characters as a specified encoding set of bytes writer.write ("This is the Chinese character to be saved!) "); Writer.close ();}}
After the program executes, the contents of the file are:
This is the Chinese character to save!
public class Inputstreamreadertest {public static void main (string[] args) throws IOException {file F=new file ("C:/test.tx T "); String charset= "UTF-8";//string charset= "iso-8859-1"; Read bytes converted into characters FileInputStream inputstream=new FileInputStream (f);//1, specifying a consistent encoding set, correctly outputting InputStreamReader reader=new InputStreamReader (Inputstream,charset);//2, no specified encoding set, using the operating system default encoding set, output garbled//inputstreamreader reader=new InputStreamReader (InputStream); StringBuffer buffer=new StringBuffer () char[] buf=new char[64];int count=0;try{while ((Count=reader.read (BUF))!=-1) { Buffer.append (Buf,0,count);}} Finally{reader.close ();} String s1=buffer.tostring (); System.out.println (s1);} }
Output:
This is the Chinese character to save!
If, we do not specify the encoding set, using the operating system default encoding set, will output garbled: HTTP Kong ionizing blemish like Blake dizzying Ying Crypto crypto Juan Po Ying 楃 锛?
The InputStreamReader class is a byte-to-character conversion bridge, and the process of InputStream to Reader specifies the encoding character set, otherwise the operating system default character set is used, and garbled issues are likely to occur. Streamdecoder is the implementation class that completes the decoding of byte-to-character. FileReader class is to read the file according to the way above, FileReader inherits the InputStreamReader class, actually reads the file stream, and then decodes it into char by Streamdecoder.
the difference between Java NIO and blocking I/Oblocking I/O communication modelIf you have a certain understanding of blocking I/O now, we know that blocking I/O is blocked when the Inputstream.read () method is called, and it waits until the data arrives (or times out) before it returns; again, the call to Serversocket.accept () method, it also blocks until a client connection is returned, and after each client connects, the server initiates a thread to process the client's request.
The communication model for blocking I/O is as follows:
If you analyze it carefully, you will find that there are some drawbacks to blocking I/O. Based on the blocking I/O communication model, I've summed up its two-point disadvantage:
1. When the client is a long time, a large number of processing threads are created. And each thread consumes stack space and some CPU time
2. Blocking can lead to frequent context switching, and most context switches may be meaningless.
In this case, the non-blocking I/O has its application foreground.
Java NIO principle and communication model
Java NiO is used in jdk1.4, which can be said to be "new I/O", or non-blocking I/O. Here's how Java NIO works:
1. All IO events are handled by a dedicated thread and are responsible for distribution.
2. Event-driven: Events arrive at the time of event, instead of synchronizing to monitor events.
3. Thread communication: The threads communicate through wait,notify and other means. Ensure that each context switch is meaningful. Reduce unnecessary thread switching.
After reading some of the information, I'll stick to the schematic diagram of the Java NiO I understand:
The Java NiO server only needs to start a dedicated thread to handle all IO events, how is this communication model implemented? Hehe, let's explore its mysteries together. Java NIO uses two-way channels (channel) for data transfer, rather than one-way streams, which allow us to register events of interest on the channel.
| Event name |
corresponding values |
| Server-side Receive client connection events |
Selectionkey.op_accept (16) |
| Client Connection service-side events |
Selectionkey.op_connect (8) |
| Read Events |
Selectionkey.op_read (1) |
| Write events |
Selectionkey.op_write (4) |
The server and the client each maintain a management channel object, which we call selector, which detects events on one or more channels (channel) . We take the server as an example, if a read event is registered on the server's selector, at some point the client sends some data to the server, blocking I/O then calls the Read () method to block the data, and the service side of NiO adds a read event to the selector. The service-side processing thread polls the selector and, if an event of interest is found when accessing selector, handles these events and, if no event of interest arrives, the processing thread blocks until the event of interest arrives.
Here's what I understand about the communication model of Java NIO:
Java NIO Server and client code implementations
Import Java.io.ioexception;import Java.net.inetsocketaddress;import Java.nio.bytebuffer;import Java.nio.channels.selectionkey;import Java.nio.channels.selector;import Java.nio.channels.socketchannel;import Java.util.iterator;public class Nioclient {//Channel manager private Selector Selector; /* Get a socket channel and do some initialization work on the channel * @param IP, IP of the connected server * @param port, port number of the connected server * @throws IOException */public void initclient (String ip,int port) throws ioexception{//get a socket channel socket Channel channel = Socketchannel.open (); Set the channel to non-blocking channel.configureblocking (false); Get a channel manager This.selector = Selector.open (); /* Client Connection server, in fact the method does not implement the connection, you need to call Channel.finishconnect () in the Listen () method to complete the connection */Channel.connect (New Inetsocketaddress ( Ip,port)); Binds the channel manager and the channel, and registers the Selectionkey.op_connect event Channel.register (This.selector, selectionkey.op_connect) for that channel; }/* * Polling is used to listen for events that need to be handled on selector, ifThere, it is processed. * @throws IOException */public void Listen () throws ioexception{//polling access selector while (true) { /* * Select a group of events that can perform I/O operations, put in selector, the client's method is not blocked, * here and the service side of the method is not the same, see API comments can know, when at least one channel is selected, * Selector's Wakeup method is called, the method returns, and for the client, the channel is always selected */Selector.select (); Gets the iterator for the selected item in selector iterator<selectionkey> ite = This.selector.selectedKeys (). Iterator (); while (Ite.hasnext ()) {Selectionkey key = (Selectionkey) ite.next (); Delete the selected key to prevent ite.remove () from being processed repeatedly; The connection event occurs if (Key.isconnectable ()) {Socketchannel channel = (Socketchannel) key.channel (); If you are connecting, complete the connection if (channel.isconnectionpending ()) {channel.fi Nishconnect (); }//set to non-blocking channel.configureblocking (FALSE); Here you can send a message to the server Oh Channel.write (bytebuffer.wrap ("ABCDEFG"). GetBytes ()); After the connection with the server is successful, in order to receive the information from the server, we need to set the Read permission to the channel Channel.register (This.selector, Selectionkey.op_read); A readable event was obtained} else if (Key.isreadable ()) {read (key); }}}} public void read (Selectionkey key) throws ioexception{Socketchannel channel = (SOC Ketchannel) Key.channel (); Bytebuffer buffer = bytebuffer.allocate (10); Channel.read (buffer); byte[] data = Buffer.array (); String msg = new string (data). Trim (); SYSTEM.OUT.PRINTLN ("Client received message:" + msg); Bytebuffer Outbuffer = Bytebuffer.wrap (Msg.getbytes ()); Channel.write (Outbuffer); } public static void Main (string[] args) throws ioexception{nioclient client = new Nioclient (); Client.initclient ("localhost", 8080); ClIent.listen (); }}
Import java.io.*;import java.net.*;import java.nio.bytebuffer;import java.nio.channels.*;import java.util.*;p ublic Class Nioserver {//Channel manager private Selector Selector; /* Get a serversocket channel and do some initialization work on the channel * @param port bound Port number * @throws IOException */public void INI Tserver (int port) throws IOException {//Get a serversocket channel serversocketchannel Serverchannel = ServerSocket Channel.open (); Set the channel to non-blocking serverchannel.configureblocking (false); Bind the ServerSocket of the channel to Port Serverchannel.socket (). bind (New Inetsocketaddress (port)); Get a channel manager This.selector = Selector.open (); /* Binds the channel manager to the channel and registers the Selectionkey.op_accept event for that channel, after registering the event, * Selector.select () returns if the event arrives, if the event does not reach Selector.select () will always block. */Serverchannel.register (selector, selectionkey.op_accept); }/* * Polling is used to listen for events that need to be handled on selector, and if so, process * @throws IOException */public void Listen () throws Ioexc eption { SYSTEM.OUT.PRINTLN ("Server started successfully! "); Polling access selector while (true) {//When the registered event arrives, the method returns; otherwise, the method will block Selector.select (); Gets the iterator for the selected item in selector, the selected item is the registered event iterator<selectionkey> ite = This.selector.selectedKeys (). Iterator (); while (Ite.hasnext ()) {Selectionkey key = (Selectionkey) ite.next (); Delete the selected key to prevent ite.remove () from being processed repeatedly; Client Request Connection Event if (key.isacceptable ()) {Serversocketchannel Server = (Serversocketchannel) key . Channel (); Obtain and client-connected channels Socketchannel Channel = Server.accept (); Set to non-blocking channel.configureblocking (false); Here you can send a message to the client Oh Channel.write (Bytebuffer.wrap ("New String" ("1234567890"). GetBytes ())); After the connection with the client is successful, in order to receive the information from the client, you need to set the Read permission to the channel Channel.register (This.selector, SelectionKey.op_read); }else if (key.isreadable ()) {read (key); }}}}/* * Handling events that read messages sent by clients * @param key * @throws IOException */public void Read (Selectionkey key) throws ioexception{//server readable message: Gets the event that occurs when the socket channel Socketchannel channel = (Socketchanne L) Key.channel (); Creates a read buffer Bytebuffer = bytebuffer.allocate (10); Channel.read (buffer); byte[] data = Buffer.array (); String msg = new string (data). Trim (); SYSTEM.OUT.PRINTLN ("Server received message:" + msg); Bytebuffer Outbuffer = Bytebuffer.wrap (Msg.getbytes ()); Channel.write (Outbuffer);//Send message back to client} public static void Main (string[] args) throws IOException {Nioser Ver server = new Nioserver (); Server.initserver (8080); Server.listen (); }}
Content from:
In-depth analysis of Java Web Technology Insider
https://www.ibm.com/developerworks/cn/java/j-lo-javaio/#resources
http://weixiaolu.iteye.com/blog/1479656
Java I/O working mechanism