I/O复习(二)——Java NIO

Java NIO

Buffer

Exam.java:

import java.nio.ByteBuffer;
import java.nio.CharBuffer;

public class Exam {
    public static void main(String[] args) {
        // 创建缓冲区的第一种方式
        CharBuffer cBuf = CharBuffer.allocate(10);
        cBuf.put('A');
        cBuf.put('B');
        cBuf.put('C');
        cBuf.put('D');
        cBuf.put('E');
        cBuf.put('F');
        cBuf.put('G');
        cBuf.put('H');
        // 回绕
        cBuf.rewind();
        while (cBuf.hasRemaining()) {
            System.out.print(cBuf.get());
        }

        System.out.println();

        // 创建缓冲区的第二种方式
        byte[] bytes = new byte[15];
        for (int i = 0; i < 15; i++) {
            bytes[i] = (byte) ('A' + i);
        }
        ByteBuffer buf = ByteBuffer.wrap(bytes);
        while (buf.hasRemaining()) {
            System.out.print((char) buf.get());
        }
    }
}

MappedChannelRead.java:

import java.io.IOException;
import java.nio.MappedByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.file.Files;
import java.nio.file.Paths;

public class MappedChannelRead {
    public static void main(String[] args) {
        // 用try-with-resources的方式获取文件的通道
        try (FileChannel fChan = (FileChannel) Files.newByteChannel(Paths.get("test.txt"))) {
            // 获取文件大小
            long fSize = fChan.size();

            // 现在,将文件映射到缓冲区。
            MappedByteBuffer mBuf = fChan.map(FileChannel.MapMode.READ_ONLY,0,fSize);

            // 从缓冲区读取和显示字节。
            for(int i = 0; i < fSize; i++){
                System.out.print((char) mBuf.get());
            }

        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

MappedChannelWrite.java:

import java.io.IOException;
import java.nio.MappedByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;

public class MappedChannelWrite {
    public static void main(String[] args) {
    
        try (FileChannel fChan = (FileChannel) Files.newByteChannel(Paths.get("test.txt"),
                StandardOpenOption.WRITE,
                StandardOpenOption.READ,
                StandardOpenOption.CREATE)) {
            // 然后将文件映射到缓存区中
            MappedByteBuffer mBuf = fChan.map(FileChannel.MapMode.READ_WRITE, 0, 26);

            // 将一些字节写入缓冲区
            for (int i = 0; i < 26; i++) {
                mBuf.put((byte) ('A' + i));
            }
            // 写入文件
            mBuf.force();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

Channel

Exam2.java:

import java.io.IOException;
import java.io.RandomAccessFile;
import java.nio.ByteBuffer;
import java.nio.CharBuffer;
import java.nio.channels.FileChannel;

public class Exam2 {
    public static void main(String[] args) throws IOException {
        RandomAccessFile aFile = new RandomAccessFile("test.txt", "rw");
        FileChannel inChannel = aFile.getChannel();

        ByteBuffer buf = ByteBuffer.allocate(10);

        int bytesRead = inChannel.read(buf);
       
        while (bytesRead != -1) {
            buf.flip();
            while(buf.hasRemaining()){
                System.out.print((char) buf.get());
            }

            buf.clear();
            bytesRead = inChannel.read(buf);

        }
        aFile.close();
    }
}

ExplicitChannelWrite.java:

import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;


public class ExplicitChannelWrite {
    public static void main(String[] args) {
    
        try (FileChannel fChan = (FileChannel) Files.newByteChannel(Paths.get("test.txt"),
                StandardOpenOption.WRITE,
                StandardOpenOption.CREATE)) {
            // 创建一个缓冲区
            ByteBuffer mBuf = ByteBuffer.allocate(26);

            // 向缓冲区中写入一些字节
            for (int i = 0; i < 26; i++) {
                mBuf.put((byte) ('A' + i));
            }

            // 重置缓冲区,以让其写入
            mBuf.rewind();

            // 将缓冲区写入输出文件
            fChan.write(mBuf);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

ExplicitChannelRead.java:

import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.SeekableByteChannel;
import java.nio.file.Files;
import java.nio.file.InvalidPathException;
import java.nio.file.Paths;


public class ExplicitChannelRead {
    public static void main(String[] args) {
        int count;
        try (SeekableByteChannel fChan = Files.newByteChannel(Paths.get("test.txt"))) {
            // 分配一个缓冲区
            ByteBuffer mBuf = ByteBuffer.allocate(128);

            do {
                // 每次调用read()时,将来自文件的数据填充mBuf指定的缓冲区
                count = fChan.read(mBuf);

                // 到达文件结尾时停止
                if (count != -1) {
                    // 回绕缓冲区以便读取
                    mBuf.rewind();
                    // 从缓冲区中读取字节,并在屏幕上显示为字符。
                    for (int i = 0; i < count; i++) {
                        System.out.print((char) mBuf.get());
                    }
                }
            } while (count != -1);

        } catch (InvalidPathException e) {
            System.out.println("Path Error " + e);
        } catch (IOException e) {
            System.out.println("I/O Error " + e);
        }
    }
}

Scatter/Gather

Exam3.java:

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;

public class Exam3 {
    public static void main(String[] args) throws IOException {
        RandomAccessFile aFile = new RandomAccessFile("test.txt", "rw");
        FileChannel inChannel = aFile.getChannel();

        ByteBuffer buf = ByteBuffer.allocate(5);
        ByteBuffer buf2 = ByteBuffer.allocate(5);

        ByteBuffer[] bufferArray = {buf, buf2};
        // Scatter
        long bytesRead = inChannel.read(bufferArray);
        while (bytesRead != -1) {
            buf.flip();
            buf2.flip();
            while(buf.hasRemaining()){
                System.out.print((char) buf.get());
            }
            while(buf2.hasRemaining()){
                System.out.print((char) buf2.get());
            }

            buf.clear();
            buf2.clear();
            bytesRead = inChannel.read(bufferArray);

        }
        aFile.close();

        // Gather
        FileOutputStream fileInputStream = new FileOutputStream("file1.txt");
        FileChannel outChannel = fileInputStream.getChannel();

        outChannel.write(bufferArray);
        fileInputStream.close();

    }
}

Pipe

Exam4.java:

import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.Pipe;

public class Exam4 {
    public static void main(String[] args) throws IOException {
        Pipe pipe = Pipe.open();

        // 写入Pipe
        Pipe.SinkChannel sinkChannel = pipe.sink();
        // 写入数据
        String newData = "New String to write to file..." + System.currentTimeMillis();
        ByteBuffer buf = ByteBuffer.allocate(48);
        buf.clear();
        buf.put(newData.getBytes());
        buf.flip();
        while (buf.hasRemaining()) {
            sinkChannel.write(buf);
        }

        // 从管道读取数据
        Pipe.SourceChannel sourceChannel = pipe.source();
        ByteBuffer buff = ByteBuffer.allocate(10);
        int bytesRead = sourceChannel.read(buff);
        while (bytesRead != -1) {
            buff.flip();
            while (buff.hasRemaining()) {
                System.out.print((char) buff.get());
            }
            buff.clear();
            bytesRead = sourceChannel.read(buff);
        }

        
        sourceChannel.close();
        sinkChannel.close();

    }
}

猜你喜欢

转载自blog.csdn.net/qq_33704186/article/details/89384575