Java中的NIO及IO

1.概述java

Java NIONew IO) 是从Java 1.4版本开始引入的一个新的IO API,能够替代标准的Java IO API
NIO与原来的IO有一样的做用和目的,可是使用的方式彻底不一样, NIO支持面向缓冲区的、基于通道的IO操做NIO将以更加高效的方式进行文件的读写操做。
数组

 

Java NIO系统的核心在于:服务器

  通道(Channel)和缓冲区(Buffer)网络

  通道表示打开到 IO 设备(例如:文件、套接字)的链接。并发

  若须要使用 NIO 系统,须要获取用于链接 IO 设备的通道以及用于容纳数据的缓冲区。而后操做缓冲区,对数据进行处理。
app

 简而言之, Channel 负责传输Buffer 负责存储
dom

 

Buffer 中的重要概念:
容量 (capacity) 表示 Buffer 最大数据容量,缓冲区容量不能为负,而且创
建后不能更改。
限制 (limit)第一个不该该读取或写入的数据的索引,即位于 limit 后的数据
不可读写。缓冲区的限制不能为负,而且不能大于其容量。
位置 (position)下一个要读取或写入的数据的索引。缓冲区的位置不能为
负,而且不能大于其限制
标记 (mark)与重置 (reset)标记是一个索引,经过 Buffer 中的 mark() 方法
指定 Buffer 中一个特定的 position,以后能够经过调用 reset() 方法恢复到这
position.
标记、 位置、 限制、 容量遵照如下不变式: 0 <= mark <= position <= limit <= capacity
socket

2.NIO与IO的区别ide

 

NIO工具

传统的IO

 

 3.缓冲区(buffer)

 

package com.zy.nio;

import org.junit.Test;

import java.nio.ByteBuffer;

/*
 * 1、缓冲区(Buffer):在 Java NIO 中负责数据的存取。缓冲区就是数组。用于存储不一样数据类型的数据
 *
 * 根据数据类型不一样(boolean 除外),提供了相应类型的缓冲区:
 * ByteBuffer
 * CharBuffer
 * ShortBuffer
 * IntBuffer
 * LongBuffer
 * FloatBuffer
 * DoubleBuffer
 *
 * 上述缓冲区的管理方式几乎一致,经过 allocate() 获取缓冲区
 *
 * 2、缓冲区存取数据的两个核心方法:
 * put() : 存入数据到缓冲区中
 * get() : 获取缓冲区中的数据
 *
 * 3、缓冲区中的四个核心属性:
 * capacity : 容量,表示缓冲区中最大存储数据的容量。一旦声明不能改变。
 * limit : 界限,表示缓冲区中能够操做数据的大小。(limit 后数据不能进行读写)
 * position : 位置,表示缓冲区中正在操做数据的位置。
 *
 * mark : 标记,表示记录当前 position 的位置。能够经过 reset() 恢复到 mark 的位置
 *
 * 0 <= mark <= position <= limit <= capacity
 *
 * 4、直接缓冲区与非直接缓冲区:
 * 非直接缓冲区:经过 allocate() 方法分配缓冲区,将缓冲区创建在 JVM 的内存中
 * 直接缓冲区:经过 allocateDirect() 方法分配直接缓冲区,将缓冲区创建在物理内存中。能够提升效率
 */
public class NioBufferDemo01 {


    @Test
    public void fn03(){
        // 间接缓冲区
        ByteBuffer buffer = ByteBuffer.allocate(1024);
        // 直接缓冲区
        ByteBuffer diretBuffer = ByteBuffer.allocateDirect(1024);
        System.out.println(buffer.isDirect());
        System.out.println(diretBuffer.isDirect());
    }


    @Test
    public void fn02(){
        String str = "qwertyuiop";
        ByteBuffer buffer = ByteBuffer.allocate(1024);
        buffer.put(str.getBytes());
        buffer.flip();

        byte[] b = new byte[buffer.limit()];
        buffer.get(b, 0, 2);
        System.out.println(new String(b, 0, 2));
        System.out.println(buffer.position());

        // mark:标记
        System.out.println("-----------------mark()----------------");
        buffer.mark();
        buffer.get(b, 2, 2);
        System.out.println(new String(b, 2, 2));
        System.out.println(buffer.position());

        // reset:恢复到mark的位置
        System.out.println("-----------------reset()----------------");
        buffer.reset();
        System.out.println(buffer.position());

        //判断缓冲区中是否还有剩余数据
        System.out.println("-----------------hasRemaining()----------------");
        System.out.println("-----------------remaining()----------------");
        if (buffer.hasRemaining()){
            System.out.println(buffer.remaining());
        }
    }


    @Test
    public void fn01(){

    String string = "zxcvbnm";

        //1. 分配一个指定大小的缓冲区
        ByteBuffer buffer = ByteBuffer.allocate(1024);

        System.out.println("-----------------allocate()----------------");
        System.out.println(buffer.position());
        System.out.println(buffer.limit());
        System.out.println(buffer.capacity());

        //2. 利用 put() 存入数据到缓冲区中
        buffer.put(string.getBytes());
        System.out.println("-----------------put()----------------");
        System.out.println(buffer.position());
        System.out.println(buffer.limit());
        System.out.println(buffer.capacity());

        //3. 切换读取数据模式
        buffer.flip();
        System.out.println("------------------flip()-------------------");
        System.out.println(buffer.position());
        System.out.println(buffer.limit());
        System.out.println(buffer.capacity());

        //4. 利用 get() 读取缓冲区中的数据
        byte[] b = new byte[buffer.limit()];
        buffer.get(b);
        System.out.println(new String(b, 0, b.length));

        System.out.println("------------------get()-------------------");
        System.out.println(buffer.position());
        System.out.println(buffer.limit());
        System.out.println(buffer.capacity());

        //5. rewind() : 可重复读
        buffer.rewind();

        System.out.println("-----------------rewind()----------------");
        System.out.println(buffer.position());
        System.out.println(buffer.limit());
        System.out.println(buffer.capacity());

        //6. clear() : 清空缓冲区. 可是缓冲区中的数据依然存在,可是处于“被遗忘”状态
        buffer.clear();

        System.out.println("------------------clear()------------------------");
        System.out.println(buffer.position());
        System.out.println(buffer.limit());
        System.out.println(buffer.capacity());

        System.out.println((char)buffer.get());
    }

}

 

4.通道

通道(Channel):由 java.nio.channels 包定义的。 Channel 表示 IO 源与目标打开的链接。

Channel 相似于传统的“流”。只不过 Channel自己不能直接访问数据, Channel 只能与Buffer 进行交互。

自己不存储任何数据,须要配合缓冲区才能完成数据传输。

 

package com.zy.nio;

import org.junit.Test;

import java.io.*;
import java.nio.ByteBuffer;
import java.nio.CharBuffer;
import java.nio.MappedByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.charset.CharacterCodingException;
import java.nio.charset.Charset;
import java.nio.charset.CharsetDecoder;
import java.nio.charset.CharsetEncoder;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;
import java.util.SortedMap;

/*
 * 1、通道(Channel):用于源节点与目标节点的链接。在 Java NIO 中负责缓冲区中数据的传输。Channel 自己不存储数据,所以须要配合缓冲区进行传输。
 *
 * 2、通道的主要实现类
 *     java.nio.channels.Channel 接口:
 *         |--FileChannel              用于读取、写入、映射和操做文件的通道。
 *         |--SocketChannel            经过 TCP 读写网络中的数据
 *         |--ServerSocketChannel      能够监听新进来的 TCP 链接,对每个新进来的链接都会建立一个 SocketChannel
 *         |--DatagramChannel          经过 UDP 读写网络中的数据通道
 *
 * 3、获取通道有三种方式
 * 1. Java 针对支持通道的类提供了 getChannel() 方法
 *         本地 IO:
 *         FileInputStream/FileOutputStream
 *         RandomAccessFile
 *
 *         网络IO:
 *         Socket
 *         ServerSocket
 *         DatagramSocket
 *
 * 2. 在 JDK 1.7 中的 NIO.2 针对各个通道提供了静态方法 open()
 * 3. 在 JDK 1.7 中的 NIO.2 的 Files 工具类的 newByteChannel()
 *
 * 4、通道之间的数据传输
 * transferFrom()
 * transferTo()
 *
 * 5、分散(Scatter)与汇集(Gather)
 * 分散读取(Scattering Reads):将通道中的数据分散到多个缓冲区中
 * 汇集写入(Gathering Writes):将多个缓冲区中的数据汇集到通道中
 *
 * 6、字符集:Charset
 * 编码:字符串 -> 字节数组
 * 解码:字节数组  -> 字符串
 *
 */
public class NioChannelDemo01 {

    // 6.指定字符集的编码与解码
    @Test
    public void fn06() throws Exception {
        Charset charset = Charset.forName("utf-8");
        // 获取编码器
        CharsetEncoder encoder = charset.newEncoder();
        // 获取解码器
        CharsetDecoder decoder = charset.newDecoder();
        CharBuffer cBuffer = CharBuffer.allocate(1024);
        cBuffer.put("好好学习,每天向上");
        cBuffer.flip();
        // 编码
        ByteBuffer bBuffer = encoder.encode(cBuffer);
        // 解码
        bBuffer.flip();
        CharBuffer charBuffer = decoder.decode(bBuffer);
        System.out.println(charBuffer);

    }

    // 5.遍历全部支持的字符集
    @Test
    public void fn05(){
        SortedMap<String, Charset> charsets = Charset.availableCharsets();
        charsets.forEach((k,v)->{
            System.out.println("item:"+k+"===============value:"+v);
        });
    }

    // 4.分散读取与汇集写入
    @Test
    public void fn04() throws Exception{
        RandomAccessFile raf = new RandomAccessFile("E:/idea.txt", "rw");
        // 获取通道
        FileChannel channel = raf.getChannel();
        // 分配指定的缓冲区的大小
        ByteBuffer buffer = ByteBuffer.allocate(100);
        ByteBuffer buffer1 = ByteBuffer.allocate(1024);
        // 分散读取
        ByteBuffer[] buffers = {buffer, buffer1};
        channel.read(buffers);
        for (ByteBuffer bf : buffers){
            bf.flip();
        }
        System.out.println("==================分散读取开始====================");
        System.out.println(new String(buffers[0].array(), 0, buffers[0].limit()));
        System.out.println(new String(buffers[1].array(), 0, buffers[1].limit()));
        System.out.println("==================分散读取结束====================");

        // 汇集写入
        RandomAccessFile raf2 = new RandomAccessFile("E:/idea01.txt", "rw");
        FileChannel channel1 = raf2.getChannel();
        channel1.write(buffers);

    }

    // 3.使用直接缓冲区完成文件的复制(较为简便的方式)
    @Test
    public void fn03(){
        FileChannel in = null;
        FileChannel out = null;
        try {
            in = FileChannel.open(Paths.get("E:/1.png"), StandardOpenOption.READ);
            out = FileChannel.open(Paths.get("E:/4.png"), StandardOpenOption.READ, StandardOpenOption.WRITE, StandardOpenOption.CREATE);

            // 方法一: in.transferTo(0, in.size(), out);
            // 方法二:
            out.transferFrom(in, 0, in.size());
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                out.close();
                in.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    // 2.使用直接缓冲区完成文件的复制(内存映射文件)(较为复杂的方式,少用)
    /*建议将直接缓冲区主要分配给那些易受基础系统的本机 I/O 操做影响的大型、持久的缓冲区。
    通常状况下,最好仅在直接缓冲区能在程序性能方面带来明显好处时分配它们*/
    @Test
    public void fn02(){
        FileChannel inChannel = null;
        FileChannel outChannel = null;
        try {
            inChannel = FileChannel.open(Paths.get("E:/1.png"), StandardOpenOption.READ);
            outChannel = FileChannel.open(Paths.get("E:/3.png"), StandardOpenOption.WRITE, StandardOpenOption.READ, StandardOpenOption.CREATE);
            // 内存映射文件,只支持byteBuffer
            MappedByteBuffer inMapBuffer = inChannel.map(FileChannel.MapMode.READ_ONLY, 0, inChannel.size());
            MappedByteBuffer outMapBuffer = outChannel.map(FileChannel.MapMode.READ_WRITE, 0, inChannel.size());
            //直接对缓冲区进行数据的读写操做
            byte[] b = new byte[inMapBuffer.limit()];
            inMapBuffer.get(b);
            outMapBuffer.put(b);
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                inChannel.close();
                outChannel.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

    }

    // 1.利用通道完成文件的复制(非直接缓冲区)
    @Test
    public void fn01(){
        FileInputStream is = null;
        FileOutputStream os = null;
        FileChannel inChannel = null;
        FileChannel outChannel = null;
        try {
            is = new FileInputStream("E:/1.png");
            os = new FileOutputStream("E:/2.png");
            // 获取通道
            inChannel = is.getChannel();
            outChannel = os.getChannel();
            // 分配指定大小的缓冲区
            ByteBuffer buffer = ByteBuffer.allocate(1024);
            // 将通道中的数据存入缓冲区中
            while (inChannel.read(buffer) != -1){
                // 切换读取数据的模式
                buffer.flip();
                // 将缓冲区的数据写入通道中
                outChannel.write(buffer);
                // 清空缓冲区
                buffer.clear();
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                outChannel.close();
                inChannel.close();
                os.close();
                is.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

}

 

5.Blocking NIO

package com.zy.nio;

import org.junit.Test;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;

/*
 * 1、使用 NIO 完成网络通讯的三个核心:
 *
 * 1. 通道(Channel):负责链接
 *
 *        java.nio.channels.Channel 接口:
 *             |--SelectableChannel
 *                 |--SocketChannel
 *                 |--ServerSocketChannel
 *                 |--DatagramChannel
 *
 *                 |--Pipe.SinkChannel
 *                 |--Pipe.SourceChannel
 *
 * 2. 缓冲区(Buffer):负责数据的存取
 *
 * 3. 选择器(Selector):是 SelectableChannel 的多路复用器。用于监控 SelectableChannel 的 IO 情况
 *
 */
public class BlockNioDemo01 {

    // 客户端
    @Test
    public void client() throws IOException {
        // 1.获取通道
        SocketChannel socketChannel = SocketChannel.open(new InetSocketAddress("127.0.0.1", 8888));
        FileChannel inChannel = FileChannel.open(Paths.get("E:/1.png"), StandardOpenOption.READ);
        // 2.分配指定的缓冲区的大小
        ByteBuffer buffer = ByteBuffer.allocate(1024);
        // 3.读取本地文件,并发送到服务端
        while (inChannel.read(buffer) != -1){
            buffer.flip();
            socketChannel.write(buffer);
            buffer.clear();
        }
        // 4.关闭通道
        inChannel.close();
        socketChannel.close();
    }

    // 服务端
    @Test
    public void server() throws IOException {
        // 1.获取通道
        ServerSocketChannel channel = ServerSocketChannel.open();
        FileChannel outChannel = FileChannel.open(Paths.get("E:/5.png"), StandardOpenOption.WRITE, StandardOpenOption.CREATE);
        // 2.绑定链接
        channel.bind(new InetSocketAddress(8888));
        // 3.获取客户端链接的通道
        SocketChannel clientChannel = channel.accept();
        // 4.分配指定的缓冲区的大小
        ByteBuffer buffer = ByteBuffer.allocate(1024);
        // 5.接收客户端的数据并保存到本地
        while (clientChannel.read(buffer) != -1){
            buffer.flip();
            outChannel.write(buffer);
            buffer.clear();
        }
        // 6.关闭资源
        clientChannel.close();
        outChannel.close();
        channel.close();

    }

}

 

package com.zy.nio;

import org.junit.Test;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;

/**
 *
 * 阻塞式NIO2
 */
public class BlockNio2Demo01 {

    // 客户端
    @Test
    public void client() throws IOException {
        // 1.获取通道
        SocketChannel socketChannel = SocketChannel.open(new InetSocketAddress("127.0.0.1", 9999));
        FileChannel fileChannel = FileChannel.open(Paths.get("E:/1.png"), StandardOpenOption.READ);
        // 2.分配指定的缓冲区的大小
        ByteBuffer buffer = ByteBuffer.allocate(1024);
        // 3.读取本地文件,并发送到服务端
        while (fileChannel.read(buffer) != -1){
            buffer.flip();
            socketChannel.write(buffer);
            buffer.clear();
        }
        socketChannel.shutdownOutput();
        // 4.接收服务端的反馈
        int len = 0;
        while ((len = socketChannel.read(buffer)) != -1){
            buffer.flip();
            System.out.println(new String(buffer.array(), 0, len));
            buffer.clear();
        }
        // 5.关闭资源
        fileChannel.close();
        socketChannel.close();
    }

    // 服务端
    @Test
    public void server() throws IOException {
        // 1.获取通道
        ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();
        FileChannel fileChannel = FileChannel.open(Paths.get("E:/6.png"), StandardOpenOption.WRITE, StandardOpenOption.CREATE);
        // 2.绑定链接
        serverSocketChannel.bind(new InetSocketAddress(9999));
        // 3.获取客户端链接的通道
        SocketChannel socketChannel = serverSocketChannel.accept();
        // 4.分配指定缓冲区的大小
        ByteBuffer buffer = ByteBuffer.allocate(1024);
        // 5.将客户端的资源保存到本地
        while (socketChannel.read(buffer) != -1){
            buffer.flip();
            fileChannel.write(buffer);
            buffer.clear();
        }
        // 6.发送反馈给客户端
        buffer.put("服务端数据接收成功".getBytes());
        buffer.flip();
        socketChannel.write(buffer);
        // 7.关闭资源
        socketChannel.close();
        fileChannel.close();
        serverSocketChannel.close();

    }
}

 

6.Non-Blocking NIO

TCP

package com.zy.nio;

import org.junit.Test;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.*;
import java.time.LocalDateTime;
import java.util.Iterator;
import java.util.Scanner;

/*
 * 1、使用 NIO 完成网络通讯的三个核心:
 *
 * 1. 通道(Channel):负责链接
 *
 *        java.nio.channels.Channel 接口:
 *             |--SelectableChannel
 *                 |--SocketChannel
 *                 |--ServerSocketChannel
 *                 |--DatagramChannel
 *
 *                 |--Pipe.SinkChannel
 *                 |--Pipe.SourceChannel
 *
 * 2. 缓冲区(Buffer):负责数据的存取
 *
 * 3. 选择器(Selector):是 SelectableChannel 的多路复用器。用于监控 SelectableChannel 的 IO 情况
 *
 * 非阻塞式NIO
 */
public class NonBlockNioDemo01 {

    // 客户端
    @Test
    public void client() throws IOException {
        // 1.获取通道
        SocketChannel socketChannel = SocketChannel.open(new InetSocketAddress("127.0.0.1", 9090));
        // 2.切换为非阻塞模式
        socketChannel.configureBlocking(false);
        // 3.分配指定大小的缓冲区
        ByteBuffer buffer = ByteBuffer.allocate(1024);
        // 4.发送消息到服务器
        Scanner scanner = new Scanner(System.in);
        while (scanner.hasNext()){
            String str = scanner.next();
            buffer.put((LocalDateTime.now().toString()+"\n"+str).getBytes());
            buffer.flip();
            socketChannel.write(buffer);
            buffer.clear();
        }
        // 5.关闭通道
        socketChannel.close();
    }

    // 服务端
    @Test
    public void server() throws IOException {
        // 1.获取通道
        ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();
        // 2.切换为非阻塞模式
        serverSocketChannel.configureBlocking(false);
        // 3.绑定链接
        serverSocketChannel.bind(new InetSocketAddress(9090));
        // 4.获取选择器
        Selector selector = Selector.open();
        // 5.将通道注册到选择器上,指定监听事件
        serverSocketChannel.register(selector, SelectionKey.OP_ACCEPT);
        // 6.轮询式的获取选择器上准备就绪的事件
        while (selector.select() > 0){
            // 7.获取当前选择器中全部注册的选择键(已就绪的监听事件)
            Iterator<SelectionKey> keyIterator = selector.selectedKeys().iterator();
            // 8.迭代获取准备就绪的事件
            while (keyIterator.hasNext()){
                SelectionKey next = keyIterator.next();
                // 9.判断具体是什么事件准备就绪
                if (next.isAcceptable()){
                    // 10.若接收就绪,则获取客户端链接
                    SocketChannel socketChannel = serverSocketChannel.accept();
                    // 11.切换为非阻塞模式
                    socketChannel.configureBlocking(false);
                    // 12.将该通道注册到选择器上
                    socketChannel.register(selector, SelectionKey.OP_READ);
                } else if (next.isReadable()){
                    // 获取读就绪通道
                    SocketChannel channel = (SocketChannel) next.channel();
                    // 读取数据
                    ByteBuffer buffer = ByteBuffer.allocate(1024);
                    int len = 0;
                    while ((len = channel.read(buffer)) > 0){
                        buffer.flip();
                        System.out.println(new String(buffer.array(), 0, len));
                        buffer.clear();
                    }
                }
                // 取消选择键
                keyIterator.remove();
            }
        }
    }
}

UDP

package com.zy.nio;

import org.junit.Test;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.DatagramChannel;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.time.LocalDateTime;
import java.util.Iterator;
import java.util.Scanner;

/**
 * UDP-NIO
 */
public class NonBlockNioDemo02 {

    // 客户端
    @Test
    public void client() throws IOException {
        // 1.获取通道
        DatagramChannel datagramChannel = DatagramChannel.open();
        // 2.切换为非阻塞模式
        datagramChannel.configureBlocking(false);
        // 3.分配指定的缓冲区大小
        ByteBuffer buffer = ByteBuffer.allocate(1024);
        // 4.发送消息到服务器
        Scanner scanner = new Scanner(System.in);
        while (scanner.hasNext()){
            String next = scanner.next();
            buffer.put((LocalDateTime.now().toString()+"\n"+next).getBytes());
            buffer.flip();
            datagramChannel.send(buffer, new InetSocketAddress("127.0.0.1",9090));
            buffer.clear();
        }
        // 5.关闭资源
        datagramChannel.close();
    }

    // 服务端
    @Test
    public void server() throws IOException {
        // 1.获取通道
        DatagramChannel datagramChannel = DatagramChannel.open();
        // 2.切换为nio状态
        datagramChannel.configureBlocking(false);
        // 3.绑定链接
        datagramChannel.bind(new InetSocketAddress(9090));
        // 4.得到选择器
        Selector selector = Selector.open();
        // 5.将通道注册到选择器上,并绑定监听事件
        datagramChannel.register(selector, SelectionKey.OP_READ);
        // 6.经过轮询方式获取选择器上准备就绪的事件
        while (selector.select() > 0){
            Iterator<SelectionKey> it = selector.selectedKeys().iterator();
            while (it.hasNext()){
                SelectionKey next = it.next();
                if (next.isReadable()){
                    ByteBuffer buffer = ByteBuffer.allocate(1024);
                    datagramChannel.receive(buffer);
                    buffer.flip();
                    System.out.println(new String(buffer.array(), 0, buffer.limit()));
                    buffer.clear();
                }
            }
            it.remove();
        }
    }

}

 

7.管道 (Pipe)
Java NIO 管道是2个线程之间的单向数据链接Pipe有一个source通道和一个sink通道。数据会被写到sink通道,从source通道读取。

package com.zy.nio;

import org.junit.Test;

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

public class PipeNioDemo01 {

    @Test
    public void fn() throws IOException {
        // 1.获取管道
        Pipe pipe = Pipe.open();
        // 2.将缓冲区中的数据写入管道
        ByteBuffer buffer = ByteBuffer.allocate(1024);
        Pipe.SinkChannel sinkChannel = pipe.sink();
        buffer.put("经过单向管道发送数据".getBytes());
        buffer.flip();
        sinkChannel.write(buffer);
        // 3.读取管道缓冲区中的数据
        Pipe.SourceChannel sourceChannel = pipe.source();
        buffer.flip();
        int len = sourceChannel.read(buffer);
        System.out.println(new String(buffer.array(), 0, len));
        sourceChannel.close();
        sinkChannel.close();
    }
}

 

8.NIO2

8.1Path Paths
java.nio.file.Path 接口表明一个平台无关的平台路径,描述了目录结构中文件的位置。
Paths 提供的 get() 方法用来获取 Path 对象:
Path get(String first, String … more) : 用于将多个字符串串连成路径。
Path 经常使用方法:
boolean endsWith(String path) : 判断是否以 path 路径结束
boolean startsWith(String path) : 判断是否以 path 路径开始
boolean isAbsolute() : 判断是不是绝对路径
Path getFileName() : 返回与调用 Path 对象关联的文件名
Path getName(int idx) : 返回的指定索引位置 idx 的路径名称
int getNameCount() : 返回Path 根目录后面元素的数量
Path getParent() :返回Path对象包含整个路径,不包含 Path 对象指定的文件路径
Path getRoot() :返回调用 Path 对象的根路径
Path resolve(Path p) :将相对路径解析为绝对路径
Path toAbsolutePath() : 做为绝对路径返回调用 Path 对象
String toString() : 返回调用 Path 对象的字符串表示形式
8.2Files
java.nio.file.Files 用于操做文件或目录的工具类。
Files经常使用方法:
Path copy(Path src, Path dest, CopyOption … how) : 文件的复制
Path createDirectory(Path path, FileAttribute<?> … attr) : 建立一个目录
Path createFile(Path path, FileAttribute<?> … arr) : 建立一个文件
void delete(Path path) : 删除一个文件
Path move(Path src, Path dest, CopyOption…how) : src 移动到 dest 位置
long size(Path path) : 返回 path 指定文件的大小
Files经常使用方法:用于判断
boolean exists(Path path, LinkOption … opts) : 判断文件是否存在
boolean isDirectory(Path path, LinkOption … opts) : 判断是不是目录
boolean isExecutable(Path path) : 判断是不是可执行文件
boolean isHidden(Path path) : 判断是不是隐藏文件
boolean isReadable(Path path) : 判断文件是否可读
boolean isWritable(Path path) : 判断文件是否可写
boolean notExists(Path path, LinkOption … opts) : 判断文件是否不存在
public static <A extends BasicFileAttributes> A readAttributes(Path path,Class<A> type,LinkOption...options) : 获取与 path 指定的文件相关联的属性。

Files经常使用方法: 用于操做内容
SeekableByteChannel newByteChannel(Path path, OpenOption…how) : 获取与指定文件的链接,how 指定打开方式。
DirectoryStream newDirectoryStream(Path path) : 打开 path 指定的目录
InputStream newInputStream(Path path, OpenOption…how):获取 InputStream 对象
OutputStream newOutputStream(Path path, OpenOption…how) : 获取 OutputStream 对象
8.3自动资源管理

Java 7 增长了一个新特性,该特性提供了另一种管理资源的方式,这种方式能自动关闭文件。

这个特性有时被称为自动资源管理(Automatic Resource Management, ARM), 该特性以 try 语句的扩展版为基础。

自动资源管理主要用于,当再也不须要文件(或其余资源)时,能够防止无心中忘记释放它们。

相关文章
相关标签/搜索