Home IT Linux Windows Database Network Programming Server Mobile  
           
  Home \ Programming \ Getting Started with Java NIO     - Analysis of Java keyword final (Programming)

- Ubuntu file security removal tool (Linux)

- How to install Laravel PHP framework on CentOS 7 / Ubuntu 15.04 (Server)

- How to use the tab in Vim carried Python code completion (Linux)

- How to modify the SQL Server auto-increment value and the corresponding solution (Database)

- Android developers learning Adapter (data adapter) (Programming)

- Automatic Clear date directory shell script (Linux)

- Ubuntu and Archlinux install Notepadqq 0.50.2 (Linux)

- To install the latest version of Shotwell 0.18 under Ubuntu (Linux)

- C language sorting instance (select, bubble, insert, binary, fast) (Programming)

- 7 extremely dangerous Linux commands (Linux)

- Linux, see picture not resolve the problem (Linux)

- php How to prevent being injected (Linux)

- Python programmers most often committed ten errors (Programming)

- Python uses multi-process pool (Programming)

- Linux operating system must know the security command (Linux)

- Let CentOS6 yum upgrade to support more source rpm package (Linux)

- Oracle 12c PDB Analysis (Database)

- Upgrading from Fedora 20 to 21 (Linux)

- Spark read more HBase tables a RDD (Server)

 
         
  Getting Started with Java NIO
     
  Add Date : 2018-11-21      
         
       
         
  NIO Getting Started

Some time ago in the company of some large processing data, and its word, extract keywords. Although basically completed the task (the effect is not particularly good), for Java has not started me back and forth spent two weeks time, I am also drunk. Of course there are knowledge related to machine learning, I think the next one after another of the recording process this time my mission, also counted as a summary.

First of all, do have such a level of G's file, in accordance with the ordinary Java I / O is certainly not the way the division of documents, I do not know what month to finish. So then the Internet to find relevant information, I have such a magical NIO.

In Java programming, I / O is the way to read the file stream, all I / O is treated as a single byte is moved by an object called a byte Stream moving again. Java new input / output (NIO) library was introduced in JDK1.4 in. NIO to make up for the deficiencies of the original I / O, which provides high-speed in standard Java code, block-oriented I / O. By definition includes a block of data, as well as through the form of a block to handle these data, NIO without using native code can take advantage of low-level optimization, which is the original I / O package can not be done.

Comparison stream block

The most important difference between the original I / O libraries and NIO way data is packaged and transmitted, the original I / O processing to stream data, and NIO in the manner of processing data blocks.

Processing data stream-oriented I / O system, once a byte, a byte input stream to generate a data stream to produce an output one byte of data.

A block-oriented I / O system for processing data in chunks. Every operation to produce or consume a block of data in one step. Processing data in blocks than byte process data much faster, even if it does not stream-oriented I / O as simplicity.

Channel and buffers

NIO channel and buffers are in the core of the object, they are used by almost every I / O operation.

Channel is an analog of the original I / O package flow. To any destination or all of the data must be from anywhere via a Channel object. A Buffer is essentially a container object. All objects are sent to a channel must be stored into the buffer; the same, read any of the data must first be read into the buffer from the channel.

What is a buffer?

Buffer is an object that contains the data to be written to or read out just now. Join in NIO Buffer objects, and reflect a new library is an important difference with the original I / O's. In the stream-oriented I / O, you write data directly to or read data directly Stream object. In the NIO library buffer all data are processed. When data is read, it is read directly in the buffer. When data is written, it is written to the buffer. NIO access data at any time in, you put it all in the buffer. Buffer is essentially an array. Usually it is a byte array, but you can also use other types of arrays. However, a buffer is not just an array. Buffer provides a structured access to data, but also tracking system read / write process.

Buffer type

The most common type of buffer is ByteBuffer. A ByteBuffer can get / set operations (ie, byte to get and set) on the underlying byte array. NIO ByteBuffer is not the only type of buffer. In fact, for each basic Java types have a kind of buffer type:

ByteBuffer
CharBuffer
ShortBuffer
IntBuffer
LongBuffer
FloatBuffer
DoubleBuffer
Every class is an instance of Buffer Buffer interface. In addition ByteBuffer, each class has a Buffer exactly the same operation, but the data types are handled differently. Because most of the standard I / O operations use ByteBuffer, so it has all the shared buffer operations as well as some specific operations.

The following look at FloatBuffer simple example:

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.nio.ByteBuffer;
import java.nio.FloatBuffer;
import java.nio.channels.FileChannel;

// UseFloatBuffer

public class UseFloatBuffer {
    
    public static void main (String [] args) throws Exception {
        
        FloatBuffer fb = FloatBuffer.allocate (10);
        for (int i = 0; i             float f = (float) ((float) i / 10 * (2 * Math.PI));
            fb.put (f);
        }
        fb.flip ();
        while (fb.hasRemaining ()) {
            float f = fb.get ();
            System.out.println (f);
        }
    }
}

What is a channel?

Channel is an object, it can read and write data. Take NIO with the original I / O to make a comparison, like a stream channel. As mentioned earlier, all data handled by Buffer objects. You will never byte write directly to the channel, on the contrary, you are to write data to include one or more byte buffer. Similarly, you will not read directly from the channel bytes, but the data is read into the buffer from the channel, and then get the byte from the buffer. In short, the general process for the NIO: Input File -> Buffer -> Channel -> Buffer -> handle data -> Buffer -> Channel -> Buffer -> output file; I / O's the general process is: the input file -> streaming -> handle data -> streaming -> output file.

Channel Type

The difference is that the flow channel and the channel is bidirectional. And just moving stream (stream must be a subclass of InputStream or OutputStream) in one direction and the channel can be used to read, write or both read and write.

In practice: NIO in reading and writing

The basic process is the read and write I / O's. Read a passage from very simple: just create a buffer, and then let the channel will read this data buffer; write is quite simple: to create a buffer, filling it with data, and then use these data to make channel to perform write operations.

Read from a file

If you use the original I / O, then we simply create a FileInputStream and read from it. In NIO, the situation is slightly different: we first get a Channel object from the FileInputStream, and then use this channel to read data.

In NIO systems, perform a read operation at any time, you are reading from the channel, but you do not read directly from the channel. Because all data is ultimately reside in the buffer, so you read the data in the buffer through the channel.

So read the file involves three steps:

(1) Get Channel from FileInputStream

(2) Create Buffer

(3) the data read from the Buffer Channel.

1 FileInputStream fin = new FileInputStream ( "read.txt");
2 FileChannel fc = fin.getChannel ();
3 ByteBuffer buffer = ByteBuffer.allocate (1024);
4 fc.read (buffer);

Write to file

In NIO written document similar to read from the file. First, get a passage from the FileOutputStream; the next step is to create a buffer zone in which put some data - in this case, data from a named array of data taken out, the final step is to write buffer.

FileOutputStream fout = new FileOutputStream ( "write.txt");
FileChannel fc = fout.getChannel ();
ByteBuffer buffer = ByteBuffer.allocate (1024);
for (int i = 0; i       buffer.put (data [i]);
}
buffer.flip ();
fc.write (buffer);

Practical exercises

We have a simple program called CopyFile.java as the basis for this exercise, all the contents of a file will be copied to another file. CopyFile.java performs three basic operations: first create a Buffer, then read in the data source file from the buffer, then the buffer is written to the target file. This procedure is repeated - read, write, read, write - until the end of the source file.

// CopyFile

import java.io. *;
import java.nio *.;
import java.nio.channels *.;

public class CopyFile {
    
    static public void main (String args []) throws Exception {
        String infile = "E: \\ Beijing Welcomes You .txt";
        String outfile = "E: \\ out.txt";

        FileInputStream fin = new FileInputStream (infile);
        FileOutputStream fout = new FileOutputStream (outfile);
        FileChannel fcin = fin.getChannel ();
        FileChannel fcout = fout.getChannel ();

        ByteBuffer buffer = ByteBuffer.allocate (1024);

        while (true) {
            buffer.clear ();
            int r = fcin.read (buffer);
            if (r == -1) {
                break;
            }
            buffer.flip ();
            fcout.write (buffer);
        }
    }
}
     
         
       
         
  More:      
 
- Ubuntu install Avast antivirus software (Programming)
- Try the command ip, ifconfig is obsolete under Linux (Linux)
- How to manage your to-do list with the Go For It on Ubuntu (Linux)
- Nginx Keepalived Nginx monitoring scripts (Server)
- MySQL 5.6.26 source install (Database)
- PPA on Ubuntu Linux installation Plank 0.8.0 (Linux)
- Nginx Installation and Configuration (Server)
- I use the desktop environment in GNU / Linux combination tool (Linux)
- MySQL multi-instance configuration (Database)
- Learning C language pointer essays (Programming)
- Java Learning: elegant string (Programming)
- Ubuntu 14.04 / 13.10 users how to install Ubuntu Touch core applications (Linux)
- Nginx Module Development - get user ip (Server)
- Spark local development environment to build (Server)
- Remote installation of Net-SNMP whole process (Linux)
- Achieve single backup of MySQL by innobackupex (Database)
- The Linux firewall is configured to use proxy (Linux)
- Oracle: RETURNING clause (Database)
- SQLite database commonly used sentences and visualization tools on MAC MeasSQLlite use (Database)
- Ubuntu 10.10 install Oracle 10g graphic tutorials (Database)
     
           
     
  CopyRight 2002-2016 newfreesoft.com, All Rights Reserved.