Java New IO

Source: Internet
Author: User
Tags event listener

Java has introduced improvements to input and output from 1.4, and related classes are located in the Java.nio package. There are several features of the new IO:

(1) Character Set encoder and decoder

(2) Non-blocking IO

(3) Memory-mapped file

1. Character Set encoders and decoders

The CharSet class represents a different character set, and you can use the Charset.forname method to get the specified name of the character set object, CharSet related classes in the Java.nio.charset package.

(1) coding

Encodes a Unicode-encoded string into a specified encoded sequence of bytes

Charset cset = Charset.forname ("UTF-8");

String str = "CharSet class";

Bytebuffer buffer = Cset.encode (str);

byte[] bytes = Buffer.array ();

(2) decoding

Decodes a sequence of bytes into a Unicode-encoded string

Charset cset = Charset.forname ("UTF-8");

Bytebuffer buffer = Bytebuffer.wrap (bytes,0,bytes.length);

String str = cset.decode (buffer). toString ();

2. Buffer class

A buffer used to hold data of the base data type, with commonly used subclasses such as Bytebuffer, Charbuffer, DoubleBuffer, Floatbuffer, Intbuffer, Longbuffer, and Shortbuffer.

The buffer has three basic properties:

Position, the position of the next element to read and write in the buffer;

The position of the first element in a buffer that is not allowed to read and write;

The capacity, the number of elements that the buffer can contain, the capacity of the buffer is fixed, and is specified when the buffer is created.

(1) Read buffer

Read buffer, which reads the data from the buffer, usually corresponds to the write method of the other class, reads out the contents of the buffer and writes to a place. Cases:

Bytebuffer  buffer = bytebuffer.allocate (n); Buffer.flip ();   // sets the bounds to the current position, resets the position to 0, and makes the buffer a readable state FileChannel   New FileOutputStream (The contents ofthe "filename"// read buffer (from position to bounds) are written to the file channel

The content from the position to the boundary is the remainder of the buffer, which is either readable or writable.

(2) Write buffer

Write buffers, that is, write data to the buffer, usually corresponding to other classes of the Read method, will read to the content write to the buffer to save. Cases:

Bytebuffer  buffer = bytebuffer.allocate (n); Buffer.clear ();   // resets the position to 0, sets the limit to capacity, and makes the buffer writable FileChannel   New FileInputStream ("filename"//read from file channel writes to buffer

3. Non-blocking IO

The Java.nio.channels package contains channel-related classes, which represent an I/O channel to a hardware device, file, network socket, and so on, and the channel is a bidirectional channel that is readable and writable. This is a significant difference between the channel and the streaming I/O in the java.io packet, and the read and write operations of the channel can be set to block/nonblocking.

The common subclasses of channel class are: FileChannel, Datagramchannel, Socketchannel, Serversocketchannel, etc., respectively, representing the channel to file, datagram, TCP socket.

The Java.nio.channels package also contains the selector class and the Selectionkey class, the Selector class represents the Multiplexer, and the Selectionkey is the channel operation attribute used in the multiplexer to mark the registration. The selector and Selectionkey can be used to implement multiplexing I/O, for example: network I/O that can implement select mode.

The following is a simple implementation of the Java implementation of select mode IO:

//Server-Side Public classServertaskImplementsrunnable{PrivateSelector Selector; PrivateServersocketchannel Serverchannel; PrivateIterator<selectionkey>Keyitera; PrivateBytebuffer Buffer;  PublicServertask ()throwsIOException {Serverchannel=Serversocketchannel.open (); //Create server-side socket channel serverchannel.socket (). Bind (NewInetsocketaddress ("127.0.0.1", 9898)); //bind to native 9898-Port Selector=Selector.open (); //Create selector multi-channel I/O multiplexer
//Set the channel non-blocking and register the channel to the Accept Event listener collection in serverchannel.configureblocking (false). Register (selector,selectionkey.op_accept); Buffer = bytebuffer.allocate (128); } @Override Public voidrun () {Selectionkey key=NULL; while(true) { Try { if(Selector.select () > 0) //Select a group of keys whose corresponding channel is already ready for an I/O operation, returning the number of selected keys {keyitera=Selector.selectedkeys (). iterator (); while(Keyitera.hasnext ()) {Key=Keyitera.next (); if(Key.isacceptable ()) //Accpet Operational Readiness {
//Accept client Connections Socketchannel Clientchannel=( (Serversocketchannel) Key.channel ()). Accept ();
//Set client socket channel non-blocking and register to read event listener collection if(Clientchannel! =NULL) clientchannel.configureblocking (false). Register (Selector,selectionkey.op_read); } Else if(Key.isreadable ()) //read operation ready {
//Read data from the client socket channel is saved to the buffer Socketchannel Clientchannel=( (Socketchannel) Key.channel ()); Buffer.clear (); Clientchannel.read (buffer); Buffer.flip (); System.out.print (Buffer.getchar ()); System.out.println (Buffer.getint ()); } keyitera.remove (); //Remove the key to indicate that it has been processed } } } Catch(IOException e) {//TODO auto-generated Catch blockE.printstacktrace (); } } }}
 //Client
Public classClienttaskImplementsrunnable{PrivateSocketchannel Channel; Private Charname; PrivateBytebuffer Buffer; Private intCount = 0; PublicClienttask (CharNamethrowsIOException { This. Name =name;
Create a client socket channel to connect to the server side
Channel= Socketchannel.open (NewInetsocketaddress ("127.0.0.1", 9898)); Buffer = bytebuffer.allocate (128); } @Override Public voidrun () { while(true) {Count++; Try{
//Writes the contents of the buffer to the client socket channel and sends it to the server-side Buffer.putchar (name); Buffer.putint (count); Buffer.flip (); Channel.write (buffer); Buffer.clear (); Thread.Sleep (1000); //hibernate 1s } Catch(IOException e) {E.printstacktrace (); } Catch(interruptedexception e) {E.printstacktrace (); } } }}
 //Main program
Public classtest{ Public Static voidMain (string[] args) {Try { NewThread (NewServertask ()). Start (); //Start server thread for(inti = 0; I < 3; i++) //Start multiple client threads {NewThread (NewClienttask ((Char) (' A ' +i)). Start (); } } Catch(Exception e) {e.printstacktrace (); } }

The server ends up receiving information from multiple clients and prints out the results:

A1b1c1a2b2c2

4. Memory-Mapped files

The operating system can use the virtual memory mechanism to map a file or part of a file into memory, and the operation of the file is much faster than the traditional file-streaming I/O, as it accesses memory.

First, create a filechannel;

Then call the FileChannel class map method to get a mappedbytebuffer from this channel, which will map this file to virtual memory. You can specify the part of the mapping file and the mapping mode, including the following three modes:

FileChannel.MapMode.READ_ONLY, read-only mode;

FileChannel.MapMode.READ_WRITE, read-write mode, the modification of the buffer will be written back to the file;

FileChannel.MapMode.PRIVATE, read-write mode, but changes to the buffer will not be written back to the file;

The file can then be read and written by the obtained Mappedbytebuffer object.

Java New IO

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.