Home IT Linux Windows Database Network Programming Server Mobile  
  Home \ Programming \ Getting Started with Java NIO     - How nodeclub constructed Docker image (Server)

- How to Install 3.16.7 CKT2 kernel in Ubuntu 14.10, Ubuntu 14.04 and its derivative versions (Linux)

- On FreeBSD 10.2 Bugzilla how to install and configure Apache SSL (Server)

- Netapp storage routine inspections and information gathering (Linux)

- How to recover deleted files in Linux systems (Linux)

- Nagios (centreon) monitoring Linux Log (Server)

- Ubuntu install video conversion tool Selene (Linux)

- Linux Monitoring Command (Linux)

- ORA-12545: Connection failed because the target host or object does not exist (Database)

- SSH without password (Linux)

- Detailed use Zabbix monitoring Nginx (Server)

- Linux installation and configuration curl command tool (Linux)

- Linux iptables firewall settings whitelist (RHEL 6 and CentOS 7) (Linux)

- Tsunami-udp accelerated network transmission (Linux)

- Writing Better Bash build script 8 (Programming)

- SteamOS installation under Ubuntu 14.04 (Linux)

- How to use the ftp tool to transfer files between Windows and Linux (Linux)

- Ubuntu Thunderbird 24.4.0 (Linux)

- Git remote repository Explanation (Linux)

- MariaDB phpMyAdmin installation and configuration issues to resolve under CentOS7 (Database)

  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:

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) {
            buffer.flip ();
            fcout.write (buffer);
- Single-node Hadoop installation notes distributed pseudo & (Server)
- CentOS7 install NTFS-3G driver (Linux)
- Installation Flow N Play- interface stylized video player on Ubuntu (Linux)
- Summary Linux bond of multi-interface load balancing (Linux)
- Logging information through the web GUI (LogAnalyzer) (Server)
- Why use Docker (Programming)
- Simple solution CC attack under Linux VPS (Linux)
- Linux set to select the appropriate level of security of the network according to deployment (Linux)
- Linux security concerns again (Linux)
- Migrate Oracle database files to ASM (Database)
- MySQL root password reset under CentOS (Database)
- Gitlab installation under CentOS 7 (Linux)
- pureftpd basis: Install, configure, implement, anonymous logon (Linux)
- Linux environment RabbitMQ installation and monitoring of plug-in installation (Linux)
- Build your own Web server under Ubuntu Linux system (Server)
- Ubuntu rights management common commands (Linux)
- How to use scientific data Docker quickly configure the development environment (Server)
- RedHat Linux 7 build yum source server (Server)
- Install Ubuntu 14.04 and Windows 8 / 8.1 dual-boot in UEFI mode (Linux)
- Eclipse Android development environment installation (Linux)
  CopyRight 2002-2016 newfreesoft.com, All Rights Reserved.