Home PC Games Linux Windows Database Network Programming Server Mobile  
  Home \ Programming \ Java NIO in the world     - How to import JNI resulting .so libraries in Android Studio (Programming)

- MySQL binlog group to submit XA (two-phase commit) (Database)

- JDK comes with tools jinfo (Linux)

- How to back up Debian system backupninja (Linux)

- How to install new fonts on Ubuntu 14.04 and 14.10 (Linux)

- Linux Samba server-side structures and the use of the client (Server)

- iOS development -Launch Image and Launchscreen (Programming)

- To install CentOS 6.5 on your hard drive under Windows 7 (Linux)

- Linux FTP setting file description (Server)

- Java precision four operations (Programming)

- Using Oracle for Oracle GoldenGate to achieve a one-way data synchronization (Database)

- CentOS 7 Docker build private warehouse registry (Linux)

- Linux productivity tools and tips (Linux)

- How to protect your eyes automatically adjust the screen brightness on Linux (Linux)

- CentOS6.5 installation Docker (Linux)

- Getting Started Linux Shell Scripting (Programming)

- Use Visual Studio Code Development TypeScript (Linux)

- Big Data Common Glossary (Linux)

- Dual system Linux (Ubuntu) into the Windows NTFS partition's mount error (Linux)

- MongoDB data replication and data slices (Database)

  Java NIO in the world
  Add Date : 2016-05-02      
  Java NIO Profile

Java NIO, namely Java New IO, version 2.0 Java IO's, since from JDK1.4. JDK1.4 previously provided are the traditional IO, which we often use InputStream / OutputStream / Reader / Writer and the like. For traditional IO, we can use the flow of decorative features, it has a Buffer function, in essence, is the use of byte [] complete. The Java NIO Buffer separate the extracted features, but also provides many features, let's look at it ~

Buffer family

Look subclass of java.nio.Buffer

For basic data types, basically corresponding Buffer class, but the most common ByteBuffer, ByteBuffer below there are two special subclasses.


First to a piece of code, a little feel for it:

public static void main (String [] args) {
    // Allocate buffer size Buffer Its essence is designated byte [] Size
    ByteBuffer buffer = ByteBuffer.allocate (10);
    printBuffer (buffer);
    buffer.put ((byte) 1);
    printBuffer (buffer);
    buffer.flip ();
    printBuffer (buffer);
public static void printBuffer (Buffer buffer) {
    System.out.println ( "--------");
    System.out.println ( "position:" + buffer.position ());
    System.out.println ( "limit:" + buffer.limit ());
    System.out.println ( "capacity:" + buffer.capacity ());
    System.out.println ( "--------");

Since you want to use ByteBuffer, bound to know how to create it! Common way to create a ByteBuffer are the following:

Allocate heap memory mode

public static ByteBuffer allocate (int capacity) {
    if (capacity <0)
        throw new IllegalArgumentException ();
    return new HeapByteBuffer (capacity, capacity);

Direct memory allocation, namely C HEAP way

  public static ByteBuffer allocateDirect (int capacity) {

        return new DirectByteBuffer (capacity);

Note that, DirectByteBuffer is a subclass of MappedByteBuffer!

Direct Packaging byte [] formed ByteBuffer

public static ByteBuffer wrap (byte [] array,
    int offset, int length) {
        try {
            return new HeapByteBuffer (array, offset, length);
        } Catch (IllegalArgumentException x) {
            throw new IndexOutOfBoundsException ();

Since ByteBuffer is atstract class, and therefore are its two concrete subclasses we use: HeapByteBuffer / MappedByteBuffer.

We can track down construction method HeapByteBuffer / DirectByteBuffer found that they actually do one thing:

Initialization byte [] as well as some properties, such as mark, position, limit, capacity.

position vs limit vs capacity

Java NIO ByteBuffer in addition to byte [], but also provides a number of attributes, so compared to traditional IO, the operation more flexible and convenient.

First is, capacity is byte [] capacity size is generally good initialized, would not be changed, and the position, limit these two properties will be with the buffer are read / write operations to change .

The next location should read: position

limit: the byte [] in the maximum effective reading position

Let's do an example of specific instructions: use ByteBuffer to copy files

public static void closeStream (Closeable ... closeable) {
    for (Closeable c: closeable) {
        if (c! = null) {
            try {
                c.close ();
            } Catch (IOException e) {
                e.printStackTrace ();

public static void main (String [] args) throws IOException {
    FileInputStream srcFile = new FileInputStream ( "E: \\ tmp \\ Shell Study Notes .pdf");
    FileOutputStream destFile = new FileOutputStream ( "E: \\ tmp \\ Shell study notes COPY.pdf");
    ByteBuffer byteBuffer = ByteBuffer.allocate (1024 * 1024);
    FileChannel in = srcFile.getChannel ();
    FileChannel out = destFile.getChannel ();
    while (in.read (byteBuffer)! = -1) {
        byteBuffer.flip ();
        out.write (byteBuffer);
        byteBuffer.clear ();
    closeStream (srcFile, destFile);

In fact, by the above code, we have revealed the three core concepts of the Java NIO 2: Buffer channel

Previously, traditional IO, we are faced with the flow, the operation is a byte, and NIO, we are faced with the buffer, the operation will be a block.

Specifically, it is this:

Read input, such as reading the file, it should be through FileInputStream / RandomAccessFile is acquired channel; create a buffer buffer; then call the read channel operation, data is read into the buffer. Write operation, and vice versa.

The above code calls two important ways of buffer: flip () / clear (), they are doing it?

Looking directly at the source:

    public final Buffer flip () {
        limit = position;
        position = 0;
        mark = -1;
        return this;

flip and did not do anything, just to limit the position to position, and the position of the position back to 0

  public final Buffer clear () {
        position = 0;
        limit = capacity;
        mark = -1;
        return this;

clear is more simple, back to the original state!

Why call them to change the limit / positon it?

You know, if channel.read (buffer), this operation is to change the position of; if we continue otherchannel.write (buffer), then the data is written it is unknown. The best way is to position the position now live to the limit, and the position is set to 0, so it will reach the contents of the buffer to re-read! The clear purpose of the call, the more simple, it is hoped the read (buffer) time to start from zero!

mark is to do what?

In the buffer, it marks the default is set to -1. Let's look at a direct relationship with the mark of two methods:

    public final Buffer mark () {
        mark = position;
        return this;

    public final Buffer reset () {
        int m = mark;
        if (m <0)
            throw new InvalidMarkException ();
        position = m;
        return this;

By mark () we use mark remember the position, and we will revert to the mark by reset () the value of the position.

So the facts became clear, we can first call mark () POSITION remember the current position, and then we do some other things. Finally, reset () POSITION back in position the next step!


allocateDirect is a way to create DirectByteBuffer, direct memory, which is used to do it?

Obviously, JVM just an ordinary user processes, and IO devices capable of dealing with the KERNEL space, JVM KERNEL need to copy into the INPUT DATA, to copy out OUTPUT DATA KERNEL. Of course, frequent copy into the copy out operation is time consuming. The DirectBuffer will skip the JVM copy into the copy out this layer.

MappedByteBuffer: memory mapped IO

We often are allocated in memory is a space after the operation is completed, write to the disk; it can not be directly allocated some space on the disk, IO for us to operate it? MappedByteBuffer is such that it will allocate some buffer on the disk cache area is operating the disk operation!

To look at the "high performance" copy papers: use MappedByteBuffer

public static void main (String [] args) throws IOException {
    // FileInputStream fis = new FileInputStream ( "E: \\ tmp \\ Shell Study Notes .pdf");
    // FileOutputStream fos = new FileOutputStream ( "E: \\ tmp \\ Shell study notes COPY.pdf");
    RandomAccessFile fis = new RandomAccessFile ( "E: \\ tmp \\ Shell study notes .pdf", "r");
    RandomAccessFile fos = new RandomAccessFile ( "E: \\ tmp \\ Shell study notes COPY.pdf", "rw");
    FileChannel in = fis.getChannel ();
    FileChannel out = fos.getChannel ();
    long size = in.size ();
    ByteBuffer buffer = out.map (MapMode.READ_WRITE, 0, size);
    in.read (buffer);
    closeStream (fis, fos);

You can see, the first use FileChannel the map method to obtain a readable, writable position = 0, for the size of the size of MappedByteBuffer, operation of the buffer will be directly reflected in the disk!

He noted that the use FileInputStream acquired CHANNEL is read-only, use FileOutputStream acquired CHANNEL is write-only and read-write permissions map Get BUFFER need therefore to take advantage of RandromAccessFile set to read and write!

Here, JAVA NIO to introduce a part of, and I know from the NIO, to start practicing the NIO, HAPPY .....
- Into the Java keyword instanceof (Programming)
- A brief introduction to some important Docker commands (Server)
- Nginx load balancing configuration (http proxy) (Server)
- Use netcat [nc] command on Linux and Unix port scan (Server)
- Oracle 11g new features of the collection of multi-column statistics (Database)
- Kubernetes (k8s) environment to build combat (Server)
- How to build Memcached Docker container (Server)
- Boost - Memory Management - smart pointers (Programming)
- Sorting algorithm of dichotomy (binary) insertion sort algorithm (Programming)
- Hadoop connection failed or stuck processing (Server)
- MySQL simple operation notes under Linux (Database)
- Use ldap implement Windows Remote Desktop Ubuntu Linux (Linux)
- 3 ways to create a lightweight, durable system of Ubuntu Linux USB disk (Linux)
- Binary tree and some basic operations with binary list (Programming)
- Android Notification (Programming)
- MNIST presentation and database conversion (Database)
- CentOS / Debian configuration Gitlab 7.1x to build self Git repository (Linux)
- Ubuntu 14.04 build Gitlab (Linux)
- Object-C in the preparation of multi-parameter function parameter is omitted (Programming)
- Ubuntu 14.04 Nvidia graphics driver installation and settings (Linux)
  CopyRight 2002-2022 newfreesoft.com, All Rights Reserved.