鍍金池/ 教程/ Java/ Java NIO分散/聚集或向量I/O
Java NIO選擇器
Java NIO ServerSocketChannel
Java NIO通道FileLock
Java NIO組件
Java NIO編碼和解碼
Java NIO包
Java NIO緩沖區(qū)
Java NIO教程
Java NIO SocketChannel
Java NIO時(shí)間服務(wù)器示例
Java NIO字符集
Java NIO通道之間的數(shù)據(jù)傳輸
Java NIO通道
Java IO與NIO比較
Java NIO管道
Java NIO分散/聚集或向量I/O

Java NIO分散/聚集或向量I/O

在Java NIO中,通道提供了稱為分散/聚集或向量I/O的重要功能。 這是一種簡(jiǎn)單但功能強(qiáng)大的技術(shù),通過(guò)這種技術(shù),使用單個(gè)write()函數(shù)將字節(jié)從一組緩沖區(qū)寫入流,并且可以使用單個(gè)read()函數(shù)將字節(jié)從流讀取到一組緩沖區(qū)中。

Java NIO已經(jīng)內(nèi)置了分散/聚集支持。它可以用于從頻道讀取和寫入頻道。

分散讀取

“分散讀取”用于將數(shù)據(jù)從單個(gè)通道讀取多個(gè)緩沖區(qū)中的數(shù)據(jù)。

下面來(lái)看看分散原理的說(shuō)明:

下面是執(zhí)行分射讀取操作的代碼示例:

public interface ScatteringByteChannel extends ReadableByteChannel  
{  
    public long read (ByteBuffer [] argv) throws IOException;  
    public long read (ByteBuffer [] argv, int length, int offset) throws IOException;  
}

聚集寫入

“聚集寫入”用于將數(shù)據(jù)從多個(gè)緩沖區(qū)寫入單個(gè)通道。

下面來(lái)看看聚集原則的簡(jiǎn)單說(shuō)明:

下面來(lái)看看看執(zhí)行聚集寫入操作的代碼示例:

public interface GatheringByteChannel extends WritableByteChannel  
{  
    public long write(ByteBuffer[] argv) throws IOException;  
    public long write(ByteBuffer[] argv, int length, int offset) throws IOException;  
}

基本散點(diǎn)/聚集示例

下面來(lái)看看兩個(gè)緩沖區(qū)的簡(jiǎn)單例子。 第一個(gè)緩沖區(qū)保存隨機(jī)數(shù),第二個(gè)緩沖區(qū)使用分散/聚集機(jī)制保存寫入的數(shù)據(jù):

package com.yiibai;

import java.io.FileOutputStream;
import java.io.FileInputStream;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.channels.ScatteringByteChannel;
import java.nio.channels.GatheringByteChannel;

public class ScatterGatherIO {
    public static void main(String params[]) {
        String data = "Scattering and Gathering example shown in yiibai.com";
        gatherBytes(data);
        scatterBytes();
    }

    /*
     * gatherBytes() is used for reading the bytes from the buffers and write it
     * to a file channel.
     */
    public static void gatherBytes(String data) {
        String relativelyPath = System.getProperty("user.dir");
        // The First Buffer is used for holding a random number
        ByteBuffer buffer1 = ByteBuffer.allocate(8);
        // The Second Buffer is used for holding a data that we want to write
        ByteBuffer buffer2 = ByteBuffer.allocate(400);
        buffer1.asIntBuffer().put(420);
        buffer2.asCharBuffer().put(data);
        GatheringByteChannel gatherer = createChannelInstance(relativelyPath+"/testout.txt", true);
        // Write the data into file
        try {
            gatherer.write(new ByteBuffer[] { buffer1, buffer2 });
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /*
     * scatterBytes() is used for reading the bytes from a file channel into a
     * set of buffers.
     */
    public static void scatterBytes() {
        String relativelyPath = System.getProperty("user.dir");
        // The First Buffer is used for holding a random number
        ByteBuffer buffer1 = ByteBuffer.allocate(8);
        // The Second Buffer is used for holding a data that we want to write
        ByteBuffer buffer2 = ByteBuffer.allocate(400);
        ScatteringByteChannel scatter = createChannelInstance(relativelyPath+"/testout.txt", false);
        // Reading a data from the channel
        try {
            scatter.read(new ByteBuffer[] { buffer1, buffer2 });
        } catch (Exception e) {
            e.printStackTrace();
        }
        // Read the two buffers seperately
        buffer1.rewind();
        buffer2.rewind();

        int bufferOne = buffer1.asIntBuffer().get();
        String bufferTwo = buffer2.asCharBuffer().toString();
        // Verification of content
        System.out.println(bufferOne);
        System.out.println(bufferTwo);
    }

    public static FileChannel createChannelInstance(String file, boolean isOutput) {
        FileChannel FChannel = null;
        try {
            if (isOutput) {
                FChannel = new FileOutputStream(file).getChannel();
            } else {
                FChannel = new FileInputStream(file).getChannel();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return FChannel;
    }
}

在上述程序中,第一個(gè)緩沖區(qū)在控制臺(tái)上打印隨機(jī)輸出,第二個(gè)緩沖區(qū)在控制臺(tái)上打印“Scattering and Gathering example shown in yiibai.com”。

它還用“Scattering and Gathering example shown in yiibai.com”替換testout.txt文件的內(nèi)容。

420
Scattering and Gathering example shown in yiibai.com