JavaIO, JavaNIO, and JavaIOJavaNIO
1. IO example
/* Byte IO */public void byteIO () throws FileNotFoundException, IOException {FileInputStream fin = new FileInputStream (new File ("D: \ test \ byteio_in.txt ")); fileOutputStream fout = new FileOutputStream (new File ("D :\\ test \ byteio_out.txt"); int c =-1; while (c = fin. read ())! =-1) {fout. write (c);} fin. close (); fout. close ();}/* character IO */public void charIO () throws FileNotFoundException, IOException {FileReader reader = new FileReader (new File ("D: \ test \ chario_in.txt "," "); FileWriter writer = new FileWriter (new File (" D: \ test \ chario_out.txt ")); char [] charArr = new char [512]; while (reader. read (charArr )! =-1) {writer. write (charArr);} reader. close (); writer. close ();}/* bufferIO */public void bufferIO () throws FileNotFoundException, IOException {BufferedInputStream bufferReader = new BufferedInputStream (new FileInputStream ("D: \ test \ bufferio_in.txt "); BufferedOutputStream bufferWriter = new BufferedOutputStream (new FileOutputStream (" D: \ test \ bufferio_out.txt "); int c =-1; while (c = bu FferReader. read ())! =-1) {bufferWriter. write (c);} bufferReader. close (); bufferWriter. close ();}2. NIO example
/* NIO */public void NIO () throws FileNotFoundException, IOException {FileInputStream fin = new FileInputStream ("D: \ test \ nio_in.txt "); fileOutputStream fout = new FileOutputStream ("D: \ test \ nio_out.txt"); FileChannel finChannel = fin. getChannel (); FileChannel foutChannel = fout. getChannel (); ByteBuffer buffer = ByteBuffer. allocate (1, 512); while (finChannel. read (buffer )! = 1) // read the cache {buffer. flip (); // the pointer jumps to the cache header foutChannel. write (buffer); buffer. clear (); // reset the buffer} fin. close (); fout. close ();}3. implementing non-blocking services using NIO
Since 1.4, Java has added the new IO feature NIO, which brings the non-blocking feature.
In the previous server processing model. when the accept () method is used, it will be blocked until a client connection is established. After each client is connected, the server will access a new connection, start a thread to process the client request. In this new thread, it will also be blocked in the read () method until the data is read.
What's the problem?
Blocking causes a large number of thread resources to be wasted. Blocking can lead to a large number of context switches. Many switches are meaningless.
So how does NIO help us solve this problem?
1) A dedicated thread is used to process all IO events and distribute them.
2). event-driven mechanism: triggered when an event arrives, rather than monitoring the event synchronously.
3). Thread communication: threads communicate through wait, notify, and other methods. Make sure that each context switch is meaningful. Reduces unnecessary thread switching.
The server and the client each maintain a management channel object, which is called selector. This object can detect events on one or more channels. Take the server as an example. If the selector of the server registers a read event and the client sends some data to the server at a certain time point, the NIO Server adds a read event to the selector. The processing thread of the server will poll to access the selector. If an event of interest arrives when the selector is accessed, the server will handle the event. If no event of interest arrives, the processing thread will be blocked until the events of interest arrive.
The following is an example of NIO Server implementation.
public class MultiPortEcho { private int ports[]; private ByteBuffer echoBuffer = ByteBuffer.allocate(1024); public MultiPortEcho(int ports[]) throws IOException { this.ports = ports; go(); } private void go() throws IOException { // Create a new selector Selector selector = Selector.open(); // Open a listener on each port, and register each one with the selector for (int i = 0; i < ports.length; ++i) { ServerSocketChannel ssc = ServerSocketChannel.open(); ssc.configureBlocking(false); ServerSocket ss = ssc.socket(); InetSocketAddress address = new InetSocketAddress(ports[i]); ss.bind(address); SelectionKey key = ssc.register(selector, SelectionKey.OP_ACCEPT); System.out.println("Going to listen on " + ports[i]); } while (true) { int num = selector.select(); Set selectedKeys = selector.selectedKeys(); Iterator it = selectedKeys.iterator(); while (it.hasNext()) { SelectionKey key = (SelectionKey) it.next(); if ((key.readyOps() & SelectionKey.OP_ACCEPT) == SelectionKey.OP_ACCEPT) { // Accept the new connection ServerSocketChannel ssc = (ServerSocketChannel) key.channel(); SocketChannel sc = ssc.accept(); sc.configureBlocking(false); // Add the new connection to the selector SelectionKey newKey = sc.register(selector,SelectionKey.OP_READ); it.remove(); System.out.println("Got connection from " + sc); } else if ((key.readyOps() & SelectionKey.OP_READ) == SelectionKey.OP_READ) { // Read the data SocketChannel sc = (SocketChannel) key.channel(); // Echo data int bytesEchoed = 0; while (true) { echoBuffer.clear(); int r = sc.read(echoBuffer); if (r <= 0) { break; } echoBuffer.flip(); sc.write(echoBuffer); bytesEchoed += r; } System.out.println("Echoed " + bytesEchoed + " from " + sc); it.remove(); } } } } static public void main(String args[]) throws Exception { int ports[] = {1234,6765,7987}; for (int i = 0; i < args.length; ++i) { ports[i] = Integer.parseInt(args[i]); } new MultiPortEcho(ports); }}
References:
Http://www.ibm.com/developerworks/cn/education/java/j-nio/j-nio.html#ibm-pcon
Http://weixiaolu.iteye.com/blog/1479656