前言

Java NIO(new/inputstream outputstream)使用通道、缓冲来操作流,所以要深刻理解这些概念,尤其是,缓冲中的数据结构(当前位置(position)、限制(limit)、容量(capacity)),这些知识点要通过写程序慢慢体会。

NIO vs  传统IO

NIO是面向缓冲、通道的;传统IO面向流

通道是双向的既可以写、也可以读;传统IO只能是单向的

NIO可以设置为异步;传统IO只能是阻塞,同步的

缓冲区结构图

NIO是面向缓冲区的,缓冲区可以理解为一块内存,有大小。缓冲区有位置、界限、容量几个概念。

capacity:容量,缓冲区的大小

limit:限制,表示最大的可读写的数量

position:当前位置,每当读写,当前位置都会加一

flip和clear方法,内部就操作这三个变量。

缓冲区常用方法

clear:将当前位置设置为0,限制设置为容量,目的是尽最大可能让字节,由通道读取到缓冲中

flip:当前位置置为限制,然后将当前位置置为0,目的是将有数据部分的字节,由缓冲写入到通道中。通常用在读与写之间。

读写文件代码

  1 package com.nio;
  2
  3 import java.io.*;
  4 import java.nio.ByteBuffer;
  5 import java.nio.channels.FileChannel;
  6 import java.nio.charset.Charset;
  7
  8 public class TestJavaNio {
  9
 10     public static String pathname = "d://read.txt";
 11     public static String filename = "d://write.txt";
 12
 13     @SuppressWarnings("resource")
 14     public static void main(String[] args) {
 15         readNIO();
 16         writeNIO();
 17         //testReadAndWriteNIO();
 18     }
 19
 20     public static void readNIO() {
 21         FileInputStream fin = null;
 22         try {
 23             fin = new FileInputStream(new File(pathname));
 24             FileChannel channel = fin.getChannel();
 25
 26             int capacity = 1000;// 字节
 27             ByteBuffer bf = ByteBuffer.allocate(capacity);
 28             System.out.println("限制是:" + bf.limit() + ",容量是:" + bf.capacity() + " ,位置是:" + bf.position());
 29             int length = -1;
 30
 31             while ((length = channel.read(bf)) != -1) {
 32
 33                 /*
 34                  * 注意,读取后,将位置置为0,将limit置为容量, 以备下次读入到字节缓冲中,从0开始存储
 35                  */
 36                 bf.clear();
 37                 byte[] bytes = bf.array();
 38                 System.out.println("start..............");
 39
 40                 String str = new String(bytes, 0, length);
 41                 System.out.println(str);
 42                 //System.out.write(bytes, 0, length);
 43
 44                 System.out.println("end................");
 45
 46                 System.out.println("限制是:" + bf.limit() + "容量是:" + bf.capacity() + "位置是:" + bf.position());
 47
 48             }
 49
 50             channel.close();
 51
 52         } catch (FileNotFoundException e) {
 53             e.printStackTrace();
 54         } catch (IOException e) {
 55             e.printStackTrace();
 56         } finally {
 57             if (fin != null) {
 58                 try {
 59                     fin.close();
 60                 } catch (IOException e) {
 61                     e.printStackTrace();
 62                 }
 63             }
 64         }
 65     }
 66
 67     public static void writeNIO() {
 68         FileOutputStream fos = null;
 69         try {
 70
 71             fos = new FileOutputStream(new File(filename));
 72             FileChannel channel = fos.getChannel();
 73             ByteBuffer src = Charset.forName("utf8").encode("你好你好你好你好你好");
 74             // 字节缓冲的容量和limit会随着数据长度变化,不是固定不变的
 75             System.out.println("初始化容量和limit:" + src.capacity() + ","
 76                     + src.limit());
 77             int length = 0;
 78
 79             while ((length = channel.write(src)) != 0) {
 80                 /*
 81                  * 注意,这里不需要clear,将缓冲中的数据写入到通道中后 第二次接着上一次的顺序往下读
 82                  */
 83                 System.out.println("写入长度:" + length);
 84             }
 85
 86         } catch (FileNotFoundException e) {
 87             e.printStackTrace();
 88         } catch (IOException e) {
 89             e.printStackTrace();
 90         } finally {
 91             if (fos != null) {
 92                 try {
 93                     fos.close();
 94                 } catch (IOException e) {
 95                     e.printStackTrace();
 96                 }
 97             }
 98         }
 99     }
100
101     public static void testReadAndWriteNIO() {
102         FileInputStream fin = null;
103         FileOutputStream fos = null;
104         try {
105             fin = new FileInputStream(new File(pathname));
106             FileChannel channel = fin.getChannel();
107
108             int capacity = 100;// 字节
109             ByteBuffer bf = ByteBuffer.allocate(capacity);
110             System.out.println("限制是:" + bf.limit() + "容量是:" + bf.capacity() + "位置是:" + bf.position());
111             int length = -1;
112
113             fos = new FileOutputStream(new File(filename));
114             FileChannel outchannel = fos.getChannel();
115
116
117             while ((length = channel.read(bf)) != -1) {
118
119                 //将当前位置置为limit,然后设置当前位置为0,也就是从0到limit这块,都写入到同道中
120                 bf.flip();
121
122                 int outlength = 0;
123                 while ((outlength = outchannel.write(bf)) != 0) {
124                     System.out.println("读," + length + "写," + outlength);
125                 }
126
127                 //将当前位置置为0,然后设置limit为容量,也就是从0到limit(容量)这块,
128                 //都可以利用,通道读取的数据存储到
129                 //0到limit这块
130                 bf.clear();
131
132             }
133         } catch (FileNotFoundException e) {
134             e.printStackTrace();
135         } catch (IOException e) {
136             e.printStackTrace();
137         } finally {
138             if (fin != null) {
139                 try {
140                     fin.close();
141                 } catch (IOException e) {
142                     e.printStackTrace();
143                 }
144             }
145             if (fos != null) {
146                 try {
147                     fos.close();
148                 } catch (IOException e) {
149                     e.printStackTrace();
150                 }
151             }
152         }
153     }
154
155 }

Java NIO 读取文件、写入文件、读取写入混合相关推荐

  1. java之通过FileChannel实现文件复制

    1.FileChanel介绍 Java NIO FileChannel是连接文件的通道,从文件中读取数据和将数据写入文件.Java NIO FileChannel类是NIO用于替代使用标准Java I ...

  2. Java NIO学习系列七:Path、Files、AsynchronousFileChannel

    相对于标准Java IO中通过File来指向文件和目录,Java NIO中提供了更丰富的类来支持对文件和目录的操作,不仅仅支持更多操作,还支持诸如异步读写等特性,本文我们就来学习一些Java NIO提 ...

  3. Java NIO学习系列二:Channel

    上文总结了Java NIO中的Buffer相关知识点,本文中我们来总结一下它的好兄弟:Channel.上文有说到,Java NIO中的Buffer一般和Channel配对使用,NIO中的所有IO都起始 ...

  4. Java Nio 之高级搬砖工(FileChannel) 一

    Java Nio 系列 Java Nio 之Buffer Java Nio 之直接内存 Java Nio 之高级搬砖工(FileChannel) 一 前言  大家对搬砖都很熟悉吧:小绿和小蓝是搬砖工, ...

  5. 使用Java中的FileChannel和ByteBuffer在文件中读取/写入文件

    过去,我讨论过RandomAccessFile以及如何将其用于在Java中进行更快的IO,在本Java NIO教程中,我们将了解如何通过使用FileChannel和ByteBuffer来使用读/写数据 ...

  6. java读取写入文件

    先来看一下java写入文件 1 public static void readTxt(String value) throws IOException { 2 FileWriter fw = null ...

  7. java : enum、创建文件和文件夹、删除文件和文件夹、获得项目绝对路径、写入数据到excel中、java代码中两种路径符号写法、读取、写入text文件...

    java : enum http://www.cnblogs.com/hyl8218/p/5088287.html 创建文件和文件夹.删除文件和文件夹 http://www.cnblogs.com/m ...

  8. java实时读取文件内容,java实时读取和写入文件

    实时读取和写入指定文件的内容 1.[代码][Java]代码 package org.log.file; import java.io.*; import java.text.SimpleDateFor ...

  9. java读取一个应用程序_Java IO – 在写入其他应用程序时读取一个大文件

    我想使用java来读取weblogic日志文件,而weblogic正在将日志写入其中(缓冲),但我只想读取内容,当我开始阅读它时. 我怎样才能做到这一点 ? public class DemoRead ...

最新文章

  1. share_ptr_c++11
  2. 查出引起死锁的进程和SQL语句
  3. iOS UITest之加载其他应用
  4. iOS UICollectionViewCell 的拖动
  5. MAC jupyter notebook
  6. pthread和互斥量条件变量函数意义速查表
  7. 深度学习在物理层信号处理中的应用研究
  8. ZStack实践汇 | ZStack平台的使用心得
  9. VUE ---- Windows7环境下安装
  10. Oracle11g常用数据字典
  11. Arduino--DS3231时钟模块
  12. java的链表(LinkedList类)
  13. ionic 配置java_ionic开发环境搭建
  14. 计算机或可编程控制器,浅谈可编程控制器的应用
  15. 游戏修改器制作教程三:内存与Cheat Engine
  16. 股市实时行情分发工具-拿来就用
  17. 美国签证面签准备材料清单
  18. linux limits.conf 生效,limits.conf不生效问题
  19. easyui mysql_Easyui 添加查询功能_EasyUI 教程
  20. python遇到错误跳过_python 如何跳过异常继续执行

热门文章

  1. spider和python的关系_Scrapy框架-Spider和CrawlSpider的区别
  2. linux 连接redis_.NetCore 使用StackExchange.Redis 连接Redis
  3. pylint警告: An attribute defined in json.encoder line 158 hides this methodpylint(method-hidden)
  4. diff测试与流量回放测试
  5. java21天打卡-day2
  6. android创建sqlite在sd卡上,在ionic3的sdcard上创建SQLite数据库
  7. if条件判断C语言,if条件判断语句,谁能帮我分析一下?
  8. 服务器日志监控系统怎么解决,服务器日志监控系统
  9. 神经网络绘图工具-总结
  10. 计算机终止程序按钮,怎样在VisualBasic中终止计算机系统呢?