JAVA NIO File section

Source: Internet
Author: User

Nio

The purpose of using NIO in Java is to improve performance, in fact, the old IO program has been optimized, and the speed has been correspondingly improved.

NIO has three main core parts: Channel, buffer, Selector. Traditional IO operates on byte streams and character streams, and NiO operates on channel and buffer (buffers), where data is always read from the channels into the buffer or written to the channel from the buffer. The Selector (selection zone) is used to listen for events on multiple channels (e.g., connection open, data arrival). Therefore, a single thread can listen to multiple data channels.

The first major difference between NIO and traditional io (abbreviated IO) is that IO is stream-oriented and NIO is buffer-oriented. The Java io-oriented stream means that one or more bytes are read from the stream every time, until all bytes are read, and they are not being slowed anywhere. In addition, it cannot move data in the stream back and forth. If you need to move the data read from the stream before and after it, you need to cache it to a buffer first. The buffering guidance method of NIO is slightly different. The data is read to a buffer that it processes later, and can be moved back and forth in the buffer if needed. This increases the flexibility of the process. However, you also need to check if the buffer contains all the data that you need to process. Also, make sure that when more data is read into the buffer, do not overwrite the data that has not been processed in the buffer.

The various streams of Io are blocked. This means that when a thread calls read () or write (), the thread is blocked until some data is read, or the data is fully written. The thread can no longer do anything during this time. NIO's nonblocking mode allows a thread to send a request to read data from a channel, but it can only get the data that is currently available and will not get anything if no data is available. Instead of keeping the thread blocked, the thread can continue to do other things until the data becomes readable. The same is true for non-blocking writes. A thread requests to write some data to a channel, but does not have to wait for it to be fully written, and the thread can do something else at the same time. Threads typically use non-blocking IO idle time to perform IO operations on other channels, so a single thread can now manage multiple input and output channels (channel).

New features offered by NIO:

    • Non-blocking IO (this is primarily reflected in network IO)
    • Memory-Mapped files
    • File lock mechanism

The core part of NiO:

    • Channels
    • Buffers
    • Selectors
Channel and Buffer

Basically, all IO starts with a channel in NiO. The Channel is a bit like a stream. Data can be read from the channel to buffer, or it can be written from buffer to the channel. Here's a diagram:

There are several types of channel and buffer. Here are some of the main channel implementations in Java NIO:

    • FileChannel
    • Datagramchannel
    • Socketchannel
    • Serversocketchannel

The following are the key buffer implementations in Java NIO:

    • Bytebuffer
    • Mappedbytebuffer
    • Charbuffer
    • DoubleBuffer
    • Floatbuffer
    • Intbuffer
    • Longbuffer
    • Shortbuffer

Selector

Note: Selector is commonly used in network IO and is not used in file IO.

Selector allows single-threaded processing of multiple Channel. If your app has multiple connections (channels) open, but the traffic is low for each connection, it's convenient to use selector. For example, in a chat server.

This is the illustration of using a selector to process 3 channel in a single thread:

To use selector, you have to register the channel with selector and then call its select () method. This method will always block to a registered channel with event readiness. Once this method returns, the thread can handle these events, with examples of events such as new connections coming in, data receiving, and so on.

FileChannel

Traditional notation:

  1. public static void Method2 () {
  2. InputStream in = null;
  3. try{
  4. In = new Bufferedinputstream (New FileInputStream ("src/nomal_io.txt"));
  5. byte [] buf = new byte[1024];
  6. int bytesread = In.read (BUF);
  7. While (bytesread! =-1)
  8. {
  9. for (int i=0;i<bytesread;i++)
  10. System. Out.print ((char) buf[i]);
  11. Bytesread = In.read (buf);
  12. }
  13. }catch (IOException e)
  14. {
  15. E.printstacktrace ();
  16. }finally{
  17. try{
  18. if (in = null) {
  19. in.close ();
  20. }
  21. }catch (IOException e) {
  22. E.printstacktrace ();
  23. }
  24. }

NiO notation:

  1. public static void Method1 () {
  2. Randomaccessfile afile = null;
  3. try{
  4. Afile = New Randomaccessfile ("src/nio.txt", "RW");
  5. FileChannel FileChannel = Afile.getchannel ();
  6. Bytebuffer buf = bytebuffer.allocate (1024);
  7. int bytesread = Filechannel.read (BUF);
  8. System. out.println (bytesread);
  9. While (bytesread! =-1)
  10. {
  11. Buf.flip ();
  12. While (Buf.hasremaining ())
  13. {
  14. System. Out.print ((char) buf.get ());
  15. }
  16. Buf.compact ();
  17. Bytesread = Filechannel.read (BUF);
  18. }
  19. }catch (IOException e) {
  20. E.printstacktrace ();
  21. }finally{
  22. try{
  23. if (afile! = null) {
  24. Afile.close ();
  25. }
  26. }catch (IOException e) {
  27. E.printstacktrace ();
  28. }
  29. }
  30. }

Using buffer generally follows these steps:

    • Allocation space (Bytebuffer BUF = bytebuffer.allocate (1024); There is another kind of allocatedirector later stated)
    • Write data to buffer (int bytesread = Filechannel.read (buf);)
    • Call the Filp () method (Buf.flip ();)
    • Read data from buffer (System.out.print (char) buf.get ());)
    • Call the Clear () method or the compact () method

JAVA NIO File section

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.