NIO流

NIO流

# (一)Java NIO 简介

Java NIO ( New IO )是从 Java 1.4 版本开始引入的一个新的 IO API ,
可以替代标准的 Java IO API 。NIO 与原来的 IO 有同样的作用和目的,但是使用的方式完全不同, NIO 支持面向缓冲区的、基于通道的 IO 操作。 NIO 将以更加高效的方式进行文件的读写操作.

#### Java IO 与 NIO 的区别

IONIO
面向流(StreamOriented)面向缓冲区(BufferOriented)
阻塞IO(BlockingIO)非阻塞IO(NonBlockingIO)
(无)选择器(Selectors)

(二)通道(Channel 与缓冲区(Buffer)

Java NIO 系统的核心在于:通道 (Channel) 和缓冲区(Buffer) 。
通道表示打开到 IO 设备 ( 例如:文件、套接字 ) 的连接。若需要使用 NIO 系统,需要获取用于连接 IO 设备的通道以及用于容纳数据的缓冲区。然后操作缓冲区,对数据进行处理。

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

缓冲区( Buffer

缓冲区( Buffer ):一个用于特定基本数据类型的容器。由 java.nio 包定义的,所有缓冲区都是 Buffer 抽象类的子类。
Java NIO 中的 Buffer 主要用于与 NIO 通道进行交互,数据是从通道读入缓冲区,从缓冲区写入通道中的。

Buffer 就像一个数组,可以保存多个相同类型的数据。
根据数据类型不同 (boolean 除外 ) ,有以下 Buffer 常用子类:
    ByteBuffer
    CharBuffer
    ShortBuffer
    IntBuffer
    LongBuffer
    FloatBuffer
    DoubleBuffer
上述 Buffer 类 他们都采用相似的方法进行管理数据,只是各自
管理的数据类型不同而已。都是通过如下方法allocate(int capacity)获取一个 Buffer对象

static XxxBuffer allocate(int capacity) : 创建一个容量为 capacity 的 XxxBuffer 对象
缓冲区的基本属性
Buffer 中的重要概念:

   容量 (capacity) : 表示 Buffer 最大数据容量,缓冲区容量不能为负,并且创
	建后不能更改。

   限制 (limit) : 第一个不应该读取或写入的数据的索引,即位于 limit 后的数据
	不可读写。缓冲区的限制不能为负,并且不能大于其容量。

   位置 (position) : 下一个要读取或写入的数据的索引。缓冲区的位置不能为
	负,并且不能大于其限制

   标记 (mark) 与重置 (reset) : 标记是一个索引,通过 Buffer 中的 mark() 方法
	指定 Buffer 中一个特定的 position ,之后可以通过调用 reset() 方法恢复到这
	个 position.
标记、位置、限制、容量遵守以下不变式:
0 <= mark <= position <= limit <= capacity
缓冲区常用方法
缓冲区存取数据的两个核心方法:

put() : 存入数据到缓冲区中
get() : 获取缓冲区中的数据
 flip(); 切换读取数据模式
 rewind() : 可重复读
 clear() : 清空缓冲区. 但是缓冲区中的数据依然存在,但是处于“被遗忘”状态
 mark() : 标记是一个索引,通过 Buffer 中的 mark() 方法
  指定 Buffer 中一个特定的 position ,之后可以通过调用 reset() 方法恢复到这
  个 position.

代码实例1

public void test1(){
    //0.定义一个数据
	String str = "abcde";
	
	//1. 分配一个指定大小的缓冲区
	ByteBuffer buf = ByteBuffer.allocate(1024);
	
	System.out.println("-----------------allocate()----------------");
	System.out.println(buf.position());
	System.out.println(buf.limit());
	System.out.println(buf.capacity());
	
	//2. 利用 put() 存入数据到缓冲区中
	buf.put(str.getBytes());
	
	System.out.println("-----------------put()----------------");
	System.out.println(buf.position());
	System.out.println(buf.limit());
	System.out.println(buf.capacity());
	
	//3. 切换读取数据模式
	buf.flip();
	
	System.out.println("-----------------flip()----------------");
	System.out.println(buf.position());
	System.out.println(buf.limit());
	System.out.println(buf.capacity());
	
	//4. 利用 get() 读取缓冲区中的数据
	byte[] dst = new byte[buf.limit()];
	buf.get(dst);
	System.out.println(new String(dst, 0, dst.length));
	
	System.out.println("-----------------get()----------------");
	System.out.println(buf.position());
	System.out.println(buf.limit());
	System.out.println(buf.capacity());
	
	//5. rewind() : 可重复读
	buf.rewind();
	
	System.out.println("-----------------rewind()----------------");
	System.out.println(buf.position());
	System.out.println(buf.limit());
	System.out.println(buf.capacity());
	
	//6. clear() : 清空缓冲区. 但是缓冲区中的数据依然存在,但是处于“被遗忘”状态
	buf.clear();
	
	System.out.println("-----------------clear()----------------");
	System.out.println(buf.position());
	System.out.println(buf.limit());
	System.out.println(buf.capacity());
	
	System.out.println((char)buf.get());
}

## 代码示例2

@Test
public void test2(){
String str = “abcde”;

	ByteBuffer buf = ByteBuffer.allocate(1024);
	
	buf.put(str.getBytes());
	
	buf.flip();
	
	byte[] dst = new byte[buf.limit()];
	buf.get(dst, 0, 2);
	System.out.println(new String(dst, 0, 2));
	System.out.println(buf.position());
	
	//mark() : 标记
	buf.mark();
	
	buf.get(dst, 2, 2);
	System.out.println(new String(dst, 2, 2));
	System.out.println(buf.position());
	
	//reset() : 恢复到 mark 的位置
	buf.reset();
	System.out.println(buf.position());
	
	//判断缓冲区中是否还有剩余数据
	if(buf.hasRemaining()){
		//获取缓冲区中可以操作的数量
		System.out.println(buf.remaining());
	}
}
Buffer的常用方法
方法**描述
Buffer clear()清空缓冲区并返回对缓冲区的引用
Buffer flip()将缓冲区的界限设置为当前位置,并将当前位置充值为0
int capacity()返回Buffer的capacity大小
boolean hasRemaining()判断缓冲区中是否还有元素
int limit()返回Buffer的界限(limit)的位置
Buffer limit(intn)将设置缓冲区界限为n,并返回一个具有新limit的缓冲区对象
Buffer mark()对缓冲区设置标记
int position()返回缓冲区的当前位置position
Buffer position(int n)将设置缓冲区的当前位置为n,并返回修改后的Buffer对象
int remaining()返回position和limit之间的元素个数
Buffer reset()将位置position转到以前设置的mark所在的位置
Buffer rewind()将位置设为为0,取消设置的mark
缓冲区的数据操作
Buffer 所有子类提供了两个用于数据操作的方法 get() 与 put() 方法

   获取 Buffer 中的数据
		get() :读取单个字节
		get(byte[] dst) :批量读取多个字节到 dst 中
		get(int index) :读取指定索引位置的字节 ( 不会移动 position)
	放入数据到 Buffer 中
		put(byte b) :将给定单个字节写入缓冲区的当前位置
		put(byte[] src) :将 src 中的字节写入缓冲区的当前位置
		put(int index, byte b) :将指定字节写入缓冲区的索引位置 ( 不会移动 position)

直接与非直接缓冲区

字节缓冲区要么是直接的,要么是非直接的。如果为直接字节缓冲区,则 Java 虚拟机会尽最大努力直接在
此缓冲区上执行本机 I/O 操作。也就是说,在每次调用基础操作系统的一个本机 I/O 操作之前(或之后),
虚拟机都会尽量避免将缓冲区的内容复制到中间缓冲区中(或从中间缓冲区中复制内容)。

直接字节缓冲区可以通过调用此类的 allocateDirect() 工厂方法 来创建。此方法返回的 缓冲区进行分配和取消
分配所需成本通常高于非直接缓冲区 。直接缓冲区的内容可以驻留在常规的垃圾回收堆之外,因此,它们对
应用程序的内存需求量造成的影响可能并不明显。所以,建议将直接缓冲区主要分配给那些易受基础系统的
本机 I/O 操作影响的大型、持久的缓冲区。一般情况下,最好仅在直接缓冲区能在程序性能方面带来明显好
处时分配它们。

直接字节缓冲区还可以通过 FileChannel 的 map() 方法 将文件区域直接映射到内存中来创建。该方法返回
MappedByteBuffer 。 Java 平台的实现有助于通过 JNI 从本机代码创建直接字节缓冲区。如果以上这些缓冲区中的某个缓冲区实例指的是不可访问的内存区域,则试图访问该区域不会更改该缓冲区的内容,并且将会在
访问期间或稍后的某个时间导致抛出不确定的异常。

字节缓冲区是直接缓冲区还是非直接缓冲区可通过调用其 isDirect() 方法来确定。提供此方法是为了能够在
性能关键型代码中执行显式缓冲区管理。
内存映射文件效率为什么高

文件i/o的读操作,会先向文件设备发起读请求,然后驱动把请求要读的数据读取到文件的缓冲区中,这个缓冲区位于内核,然后再把这个缓冲区中的数据复制到程序虚拟地址空间中的一块区域中。

文件i/o的写操作,会向文件设备发起写请求,驱动把要写入的数据复制到程序的缓冲区中,位于用户空间,然后再把这个缓冲区的数据复制到文件的缓冲区中。

内存映射文件,是把位于硬盘中的文件看做是程序地址空间中一块区域对应的物理存储器,文件的数据就是这块区域内存中对应的数据,读写文件中的数据,直接对这块区域的地址操作,就可以,减少了内存复制的环节。

所以说,内存映射文件比起文件I/O操作,效率要高,而且文件越大,体现出来的差距越大。

通道( Channel

Java  为  Channel  接口提供的最主要实现类如下
本地文件传输通道
FileChannel :用于读取、写入、映射和操作文件的通道

网络数据传输的通道
DatagramChannel :通过  UDP  读写网络中的数据通道
SocketChannel :通过  TCP  读写网络中的数据。
ServerSocketChannel :可以监听新进来的  TCP  连接,对每一个新进来的连接都会创建一个  SocketChannel 
获取通道的方法

方式一

获取通道的一种方式是对支持通道的对象调用
getChannel()  方法。支持通道的类如下:
	本地I/O
	FileInputStream
  	FileOutputStream
   	RandomAccessFile
   	
   	网络 I/O
   	DatagramSocket
   	Socket
	ServerSocket
	
获取通道的其他方式是使用  Files  类的静态方法  newByteChannel()  获取字节通道。或者通过通道的静态方法  open()  打开并返回指定通道。
例如: 
在 JDK 1.7 中的 NIO.2 针对各个通道提供了静态方法 open()
//打开一个读取的通道
FileChannel in = FileChannel.open(Paths.get("MyTest.java"), StandardOpenOption.READ);
//打开一个写的通道
FileChannel out = FileChannel.open(Paths.get("MyTest.java"),StandardOpenOption.READ, StandardOpenOption.WRITE, StandardOpenOption.CREATE);
在 JDK 1.7 中的 NIO.2 的 Files 工具类的 newByteChannel()
public class Mytext {
    public static void main(String[] args) throws IOException {
        FileInputStream inputStream = new FileInputStream("");
        FileOutputStream outputStream = new FileOutputStream("");
        FileChannel channel = inputStream.getChannel();
        FileChannel channel1 = outputStream.getChannel();
        ByteBuffer byteBuffer = ByteBuffer.allocate(1024);
        //读写文件
        while (channel.read(byteBuffer)!=-1){
            //切换读取模式
            byteBuffer.flip();
            //写数据
            channel1.write(byteBuffer);
            //清空缓冲区
            byteBuffer.clear();
        }
        //释放资源
        inputStream.close();
        outputStream.close();
      channel.close();
      channel1.close();
    }
}

### 方式2

### (//获取通道的方式2 通过FileChannel中的静态方法 open()可以打开一个通道)

public class Mytext2 {
    public static void main(String[] args) throws IOException {
        FileChannel open = FileChannel.open(Paths.get("E:\\音乐\\歌曲大合唱.mp3"), StandardOpenOption.READ);
        FileChannel open1 = FileChannel.open(Paths.get("C:\\2019-07-20\\歌曲大合唱.mp3"), StandardOpenOption.WRITE, StandardOpenOption.CREATE);
        ByteBuffer byteBuffer = ByteBuffer.allocate(1024 * 8);
        while (open.read(byteBuffer)!=-1){
            //切换读取模式
            byteBuffer.flip();//position 0 limit
            open1.write(byteBuffer);
            //清空
            byteBuffer.clear();
        }
        //释放资源
        open.close();
        open1.close();
    }
}

代码演示复制文件

 使用非直接缓冲区复制文件

public static void main(String[] args) throws IOException {
        //创建文件输入输入流
        FileInputStream in = new FileInputStream("短发.mp3");
        FileOutputStream out = new FileOutputStream("短发2.mp3");
        //文件输入输入流的getChannel()方法获取通道
        FileChannel inChannel = in.getChannel();
        FileChannel outChannel = out.getChannel();
        //获取非直接缓冲区
        ByteBuffer byteBuffer = ByteBuffer.allocate(1024);
        //将通道中的数据放入到缓冲区中
        while (inChannel.read(byteBuffer) != -1) {
            //切换读取数据的模式
            byteBuffer.flip();
            //将缓冲区中的数据写入通道中
            outChannel.write(byteBuffer);
            //清空缓冲区
            byteBuffer.clear();
        }
        //释放资源
        in.close();
        out.close();
        inChannel.close();
        outChannel.close();
}
 使用直接缓冲区复制文件

public static void main(String[] args) throws IOException {
        //创建文件输入输入流
        FileInputStream in = new FileInputStream("短发.mp3");
        FileOutputStream out = new FileOutputStream("短发2.mp3");
        //文件输入输入流的getChannel()方法获取通道
        FileChannel inChannel = in.getChannel();
        FileChannel outChannel = out.getChannel();
        //获取非直接缓冲区
        ByteBuffer byteBuffer = ByteBuffer.allocate(1024);
        //将通道中的数据放入到缓冲区中
        while (inChannel.read(byteBuffer) != -1) {
            //切换读取数据的模式
            byteBuffer.flip();
            //将缓冲区中的数据写入通道中
            outChannel.write(byteBuffer);
            //清空缓冲区
            byteBuffer.clear();
        }
        //释放资源
        in.close();
        out.close();
        inChannel.close();
        outChannel.close();
    }

通道之间的数据传输

  • 通道之间的数据传输 用的也是直接缓冲区的方式
    
    - transferFrom()
    - transferTo()
    
    public class MyTest5 {
        public static void main(String[] args) throws IOException {
            //通道中的文件传输
            FileChannel inChannel = FileChannel.open(Paths.get("歌曲串烧.mp3"), StandardOpenOption.READ);
    
            FileChannel outChanle = FileChannel.open(Paths.get("歌曲串烧7.mp3"), StandardOpenOption.WRITE, StandardOpenOption.CREATE);
            //站在输入通道的角度
            //inChannel.transferTo(0,inChannel.size(),outChanle);
            //站在输出通道的角度
            outChanle.transferFrom(inChannel,0,inChannel.size());
              inChannel.close();
            outChannel.close();
        
    }
    
分散 (Scatter)和聚集(Gather)

分散读取( Scattering Reads )是指从 Channel 中读取的数据“分散”到多个Buffer缓冲区中

注意:按照缓冲区的顺序,从Channel中读取的数据依次将Buffer填满。

聚集写入( Gathering Writes )是指将多个 Buffer缓冲区 中的数据“聚集”到 Channel 。

注意:按照缓冲区的顺序,写入position和limit之间的数据到Channel

 public static void main(String[] args) throws IOException {
        RandomAccessFile in = new RandomAccessFile("E:\\demo.txt", "rw");
        RandomAccessFile out = new RandomAccessFile("E:\\democopy.txt", "rw");
        //获取读取通道
        FileChannel inChannel = in.getChannel();
        //创建多个缓冲区
        ByteBuffer buffer1 = ByteBuffer.allocate(100);
        ByteBuffer buffer2 = ByteBuffer.allocate(1024);
        //分散读取到多个缓冲区中
        ByteBuffer[] byteBuffers=new ByteBuffer[]{buffer1,buffer2};//把多个缓冲区放到一个大的数组中
        long read = inChannel.read(byteBuffers);//把这个大的缓冲区传进去

​    //当然我们可以看看,每个缓冲区中读入的数据
​    //byteBuffers[0].flip(); //切换到读取模式 看一下第一个缓冲区,读入的100个字节
​    //byte[] array = byteBuffers[0].array();//把ByteBuffer转换成字节数组
​    //String s = new String(array, 0, byteBuffers[0].limit());
​    //System.out.println(s);

​    //把每个缓冲区,切换到读取模式
​    for (ByteBuffer buffer : byteBuffers) {
​        buffer.flip();
​    }
​    //聚集写入
​    FileChannel outChannel = out.getChannel();
​    outChannel.write(byteBuffers);

​    //释放资源
​    inChannel.close();
​    outChannel.close();
}
FileChannel 的常用方法
方法描述
int read(ByteBufferdst*)*从Channel中读取数据到ByteBuffer
long read(ByteBuffer*[]dsts)*将Channel中的数据“分散”到ByteBuffer[]
int write(ByteBuffersrc*)*将ByteBuffer中的数据写入到Channel
long write(ByteBuffer[] srcs)将ByteBuffer[]中的数据“聚集”到Channel
long position()返回此通道的文件位置
FileChannel position(long p)设置此通道的文件位置
long size()返回此通道的文件的当前大小
FileChannel truncate(long s)将此通道的文件截取为给定大小
void force(boolean metaData)强制将所有对此通道的文件更新写入到存储设备中
JDK1.7之后Files 类中获取通道的静态方法newByteChannel()

Files.newByteChannel(Paths.get("demo.txt"), StandardOpenOption.READ);
FileChannel outChannel = (FileChannel)Files.newByteChannel(Paths.get("demo999.txt"), StandardOpenOption.READ, StandardOpenOption.WRITE, StandardOpenOption.CREATE);
案例
FileChannel inChannel = (FileChannel) Files.newByteChannel(Paths.get("demo.txt"), StandardOpenOption.READ);
        FileChannel outChannel = (FileChannel) Files.newByteChannel(Paths.get("demo999.txt"), StandardOpenOption.READ, StandardOpenOption.WRITE, StandardOpenOption.CREATE);
        //获取非直接缓冲区
        ByteBuffer byteBuffer = ByteBuffer.allocate(1024);
        //将通道中的数据放入到缓冲区中
        while (inChannel.read(byteBuffer) != -1) {
            //切换读取数据的模式
            byteBuffer.flip();
            //将缓冲区中的数据写入通道中
            outChannel.write(byteBuffer);
            //清空缓冲区
            byteBuffer.clear();
        }

Files 类中复制文件的方法

static long copy(InputStream in, Path target, CopyOption... options) 
将所有字节从输入流复制到文件。 

static long copy(Path source, OutputStream out) 
将从文件到输出流的所有字节复制到输出流中。

static Path copy(Path source, Path target, CopyOption... options) 
将一个文件复制到目标文件
 //StandardCopyOption.REPLACE_EXISTING 可选参数,复制文件,如果文件存在就替换
 //如果不写这个参数,就是文件存在,就报错,不会覆盖
        Files.copy(new FileInputStream("demo.txt"), Paths.get("demo55.txt"), StandardCopyOption.REPLACE_EXISTING);
        

​    Files.copy(Paths.get("demo55.txt"),new FileOutputStream("demo66.txt"));
​    
​    Files.copy(Paths.get("demo.txt"), Paths.get("demo77.txt"), StandardCopyOption.REPLACE_EXISTING);

Path 与 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 对象的字符串表示形式

Files 类常用方法

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 指定文件的大小

static Path write(Path path, Iterable<? extends CharSequence> lines, OpenOption... options) 可以将List集合中的数据写到文件中
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 指定的文件相关联的属性。
		例子:
		BasicFileAttributes att = Files.readAttributes(Paths.get("歌曲串烧.mp3"), BasicFileAttributes.class);
            //获取文件的属性
            att.creationTime().toMillis();

​        att.lastAccessTime().toMillis();

​        att.lastModifiedTime().toMillis();

​		
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 对像
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值