Java学习-IO流-read()和write()详解

来源:互联网 发布:郭天祥十天学会单片机4 编辑:程序博客网 时间:2024/06/11 02:11

read()

read()为FileInputStream中的方法,用以返回值为数组中的字节个数或者传入的真实字节个数或者-1

三种用法:

         1.read () 方法,这个方法 从输入流中读取数据的下一个字节。返回 0  255 范围内的 int 字节值。如果因为已经到达流末尾而没有可用的字节,则返回值 -1 

         2. read (byte[] b,int off,int len) 方法, 将输入流中最多 len 个数据字节读入 byte 数组。尝试读取 len 个字节,但读取的字节也可能小于该值。以整数形式返回实际读取的字节数。

         3.  read (byte[] b) 方法, 从输入流中读取一定数量的字节,并将其存储在缓冲区数组 b 中。以整数形式返回实际读取的字节数。

public class FileCopy {/* * 文件复制  缓存区的使用*/public static void main(String[] args) {// TODO Auto-generated method stub//定义缓冲区大小,决定一次取出字节大小byte[] buffer= new byte[19];//存FileInputStream.read('缓冲区')返回值,当其值为-1则说明到文件尾,不能再被读取int numberRead = 0; //定义两个文件流存储文件FileInputStream input = null;FileOutputStream output = null;try {input = new FileInputStream("D:/apps/test/test.txt");output = new FileOutputStream("D:/apps/test/test2.txt");//若文件不存在会自动创建。            //检测read(byte[] b)读取的过程,read每次读取的长度由缓冲区b的大小决定//do {//numberRead = input.read(buffer);//System.out.println(numberRead);//} while (numberRead!=-1);while((numberRead = input.read(buffer)) != -1) {//numberRead的目的在于防止最后一次读取的字节小于buffer长度,  //write(byte[]b,int off,int len)要求off+len<b.length且 off*len!=0否则会抛出(IndexOutOfBoundsException) 将b中len个字节按顺序写入输出流从b[off]开始,到b[off+len]Q:off为负是什么情况output.write(buffer,0,numberRead);//否则会自动填充为0 write(数组,0,写入字节数)}} catch (final IOException e) {// TODO: handle exceptione.printStackTrace();}finally {//finally块是为了释放占用的资源,不论是否有异常都要执行try {//FileInputStream是有缓冲区的,所以用完之后必须关闭,否则可能导致内存占满,数据丢失。 input.close();output.close();} catch (IOException e2) {// TODO: handle exceptione2.printStackTrace();//控制台打印异常}}}}