java nio

2023-09-08  本文已影响0人  追风还是少年

ByteBuffer

Buffer属性:

以上属性的大小关系:
0 <= mark <= position <= limit <= capacity

Buffer操作:

import java.nio.ByteBuffer;

public class ByteBufferTest {
    public static void main(String[] args) {
        // HeapByteBuffer
        ByteBuffer byteBuffer = ByteBuffer.allocate(6);
       // DirectByteBuffer
       // ByteBuffer byteBuffer = ByteBuffer.allocateDirect(6);
        // 1、初始化容量为6的ByteBuffer
        print("1、初始化容量为6的ByteBuffer", byteBuffer);


        byteBuffer.putInt(1);
        //2、写入4个字节数据后
        print("2、写入4个字节数据后", byteBuffer);

        byteBuffer.flip();
        //3、调用flip()方法切换为读模式后
        print("3、调用flip()方法切换为读模式后", byteBuffer);

        byteBuffer.get();
        //4、读取一个字节数据后
        print("4、读取一个字节数据后", byteBuffer);

        int remainding = byteBuffer.remaining();
        //5、调用remaining()方法获取剩余未读或未写字节数
        System.out.println("5、调用remaining()方法获取剩余未读或未写字节数: " + remainding);

        byteBuffer.clear();
        //6、再次调用flip()方法切换为写模式后
        print("6、调用clear()方法", byteBuffer);

    }

    public static void print(String title,ByteBuffer byteBuffer){
        System.out.print(title + ": position = " + byteBuffer.position());
        System.out.print(", ");
        System.out.print("limit = " + byteBuffer.limit());
        System.out.print(", ");
        System.out.print("capacity = " + byteBuffer.capacity());
        System.out.println();
    }
}

日志输出

1、初始化容量为6的ByteBuffer: position = 0, limit = 6, capacity = 6
2、写入4个字节数据后: position = 4, limit = 6, capacity = 6
3、调用flip()方法切换为读模式后: position = 0, limit = 4, capacity = 6
4、读取一个字节数据后: position = 1, limit = 4, capacity = 6
5、调用remaining()方法获取剩余未读或未写字节数: 3
6、调用clear()方法: position = 0, limit = 6, capacity = 6
image.png image.png image.png

FileChannel

FileInputStream/FileOutputStream与FileChannel对比:

方法:

创建FileChannel方式:

public static FileChannel open(Path path, OpenOption... options) throws IOException

public static FileChannel open(Path path, Set<? extends OpenOption> options, FileAttribute<?>... attrs) throws IOException

OpenOption主要用于控制文件的操作模式:
(1) READ:只读方式
(2) WRITE:只写方式
(3)APPEND:只追加方式
(4)CREATE:创建新文件
(5)CREATE_NEW:创建新文件,如果存在则失败
(6)TRUNCATE_EXISTING:如果以读方式访问文件,它的长度将被清除至0

Path path = FileSystems.getDefault().getPath("D:/test.txt");
FileChannel channel2 = FileChannel.open(path, StandardOpenOption.READ);
FileInputStream inputStream = new FileInputStream("D:/test.txt");
FileChannel channel = inputStream.getChannel();

FileOutputStream outputStream = new FileOutputStream("D:/test.txt");
FileChannel channel1 = outputStream.getChannel();
this.fileChannel = new RandomAccessFile(this.file, "rw").getChannel();
this.mappedByteBuffer = this.fileChannel.map(MapMode.READ_WRITE, 0, fileSize);
上一篇 下一篇

猜你喜欢

热点阅读