一、概述

  读和写是I/O的基本过程。从一个通道中读取只需创建一个缓冲区,然后让通道将数据读到这个缓冲区。写入的过程是创建一个缓冲区,用数据填充它,然后让通道用这些数据来执行写入操作。

二、从文件中读取

  1、原始I/O读文件

  如果使用原来的I/O,那么只需要创建一个FileInputStream并从它那里读取,示例代码如下:

public class BioTest
{
public static void main(String[] args) throws IOException
{
FileInputStream in=null;
try
{
in=new FileInputStream("src/main/java/data/nio-data.txt");
int b;
while((b=in.read())!=-1)
{
//一次读一个字节
System.out.print((char)b);
}
}
catch (FileNotFoundException e)
{
e.printStackTrace();
} }
}

  2、NIO读文件

  在NIO系统中,任何时候执行一个读操作,都是从通道中读取,所有的数据最终都是驻留在缓冲区中。读文件涉及三个步骤:

  1. 从FileInPutStream获取Channel
  2. 创建Buffer
  3. 将数据从Channel读到Buffer中

  示例代码如下:

    //读文件
private static void readFileNio()
{
FileInputStream fileInputStream;
try
{
fileInputStream = new FileInputStream("src/main/java/data/nio-data.txt");
FileChannel fileChannel=fileInputStream.getChannel();//从 FileInputStream 获取通道
ByteBuffer byteBuffer=ByteBuffer.allocate(1024);//创建缓冲区
int bytesRead=fileChannel.read(byteBuffer);//将数据读到缓冲区
while(bytesRead!=-1)
{
/*limit=position
* position=0;
*/
byteBuffer.flip();
//hasRemaining():告知在当前位置和限制之间是否有元素
while (byteBuffer.hasRemaining())
{
System.out.print((char) byteBuffer.get());
}
/*
* 清空缓冲区
* position=0;
* limit=capacity;
*/
byteBuffer.clear();
bytesRead = fileChannel.read(byteBuffer);
}
} catch (FileNotFoundException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
}

三、写入文件  

  1、原始I/O写文件

  private static void writeFile()
{
FileOutputStream out=null;
try
{
out=new FileOutputStream("src/main/java/data/nio-data.txt");
out.write("hello".getBytes());
}
catch(Exception e)
{
e.printStackTrace();
}
}

  2、NIO写入文件

  //写文件
private static void writeFileNio()
{
try
{
RandomAccessFile fout = new RandomAccessFile("src/main/java/data/nio-data.txt", "rw");
FileChannel fc=fout.getChannel();
ByteBuffer buffer=ByteBuffer.allocate(1024);
buffer.put("hi123".getBytes());
buffer.flip();
try
{
fc.write(buffer);
} catch (IOException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
}
catch (FileNotFoundException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
}

四、读写结合

  将一个文件的所有内容拷贝到另一个文件中。CopyFile.java 执行三个基本操作:首先创建一个 Buffer,然后从源文件中将数据读到这个缓冲区中,然后将缓冲区写入目标文件。这个程序不断重复 ― 读、写、读、写 ― 直到源文件结束。示例代码如下:

//拷贝文件
private static void copyFile()
{
FileInputStream in=null;
FileOutputStream out=null;
try
{
in=new FileInputStream("src/main/java/data/in-data.txt");
out=new FileOutputStream("src/main/java/data/out-data.txt");
FileChannel inChannel=in.getChannel();
FileChannel outChannel=out.getChannel();
ByteBuffer buffer=ByteBuffer.allocate(1024);
int bytesRead = inChannel.read(buffer);
while (bytesRead!=-1)
{
buffer.flip();
outChannel.write(buffer);
buffer.clear();
bytesRead = inChannel.read(buffer);
}
}
catch (FileNotFoundException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
}

Java NIO中的读和写的更多相关文章

  1. NIO 中的读和写

    概述 读和写是I/O的基本过程.从一个通道中读取很简单:只需创建一个缓冲区,然后让通道将数据读到这个缓冲区中.写入也相当简单:创建一个缓冲区,用数据填充它,然后让通道用这些数据来执行写入操作. 从文件 ...

  2. Java NIO中核心组成和IO区别

    1.Java NIO核心组件 Java NIO中有很多类和组件,包括Channel,Buffer 和 Selector 构成了核心的API.其它组件如Pipe和FileLock是与三个核心组件共同使用 ...

  3. Java NIO中的Buffer 详解

    Java NIO中的Buffer用于和NIO通道进行交互.如你所知,数据是从通道读入缓冲区,从缓冲区写入到通道中的.缓冲区本质上是一块可以写入数据,然后可以从中读取数据的内存.这块内存被包装成NIO ...

  4. Java NIO中的缓冲区Buffer(一)缓冲区基础

    什么是缓冲区(Buffer) 定义 简单地说就是一块存储区域,哈哈哈,可能太简单了,或者可以换种说法,从代码的角度来讲(可以查看JDK中Buffer.ByteBuffer.DoubleBuffer等的 ...

  5. java的poi技术读,写Excel[2003-2007,2010]

    在上一篇blog:java的poi技术读取Excel[2003-2007,2010] 中介绍了关于java中的poi技术读取excel的相关操作 读取excel和MySQL相关: java的poi技术 ...

  6. java NIO中的buffer和channel

    缓冲区(Buffer):一,在 Java NIO 中负责数据的存取.缓冲区就是数组.用于存储不同数据类型的数据 根据数据类型不同(boolean 除外),提供了相应类型的缓冲区:ByteBufferC ...

  7. 转载Java NIO中的Files类的使用

    Java NIO中的Files类(java.nio.file.Files)提供了多种操作文件系统中文件的方法. Files.exists() Files.exits()方法用来检查给定的Path在文件 ...

  8. JAVA NIO中的Channels和Buffers

    前言 Channels和Buffers是JAVA NIO里面比较重要的两个概念,NIO正是基于Channels和Buffers进行数据操作,且数据总是从Channels读取到Buffers,或者从Bu ...

  9. java NIO中的Reactor相关知识汇总 (转)

    一.引子 nio是java的IO框架里边十分重要的一部分内容,其最核心的就是提供了非阻塞IO的处理方式,最典型的应用场景就是处理网络连接.很多同学提起nio都能说起一二,但是细究其背后的原理.思想往往 ...

随机推荐

  1. Mysql 字符串截取

    1.从左开始截取字符串 left(str, length) 说明:left(被截取字段,截取长度) 例:select left(content,200) as abstract from my_con ...

  2. Difference between LET and LET* in Common LISP

    Difference between LET and LET* in Common LISP   LET   Parallel binding which means the bindings com ...

  3. JRE_HOME environment variable is not defined correctly This environment variableis needed to run this program

    已经安装了JDK1.7 和对应JRE 安装了tomcat8 都是解压版 并设置了JAVA_HOME.JRE_HOME 但Tomcat在启动过程中找不到 错误: the JRE_HOME environ ...

  4. 论一次iOS面试

    最近觉得现在所在公司平台用户量太少,自身技术已经到了一个瓶颈,是时候需要换一个用户量多的平台,好好研究下iOS的性能优化.内存优化等问题了. 所面试的公司由于一些默认的规定,就不多说了,大致是面了一个 ...

  5. const ,static,inline

    const: 1 定义变量 ,如下写法都可以: TYPE const ValueName = value;                  const TYPE ValueName = value; ...

  6. Java分布式应用技术架构介绍

    分布式架构的演进 系统架构演化历程-初始阶段架构

  7. 解析表达式到lucene.net的Query

    查询的时候有自己的查询格式,为了统一并且方便的搜索lucene.net 于是就写了个解析格式,大体上覆盖了几乎所有的lucene.net的query了.当然少了公共扩展库里包含的regexQuery, ...

  8. Netty5 + Protobuf 使用

    1. 安装开发环境 1.1 Netty环境 这里我使用Netty5.0.0版本 到这里下载即可http://netty.io/ 下载netty-all-5.0.0.Alpha2.jar 这个jar包简 ...

  9. 关于win7和xp的屏设置类

    DisplayInfo.h #pragma once enum WinVerDef { WIN_VER_UNKNOWN = -, WIN_VER_95 = , WIN_VER_98, WIN_VER_ ...

  10. windows下mysql开启远程访问权限

    1.mysql -u root -p 2.use mysql 3.GRANT ALL PRIVILEGES ON *.* TO 'root'@'%' IDENTIFIED BY '密码' WITH G ...