zoukankan      html  css  js  c++  java
  • Java IO流学习总结

    Java流类图结构:

    一:输入输出流

    流的概念和作用

    流是一组有顺序的,有起点和终点的字节集合,是对数据传输的总称或抽象。即数据在两设备间的传输称为流,流的本质是数据传输,根据数据传输特性将流抽象为各种类,方便更直观的进行数据操作。

    IO流的分类

    • 根据处理数据类型的不同分为:字符流和字节流
    • 根据数据流向不同分为:输入流和输出流

    字符流和字节流

    字符流的由来: 因为数据编码的不同,而有了对字符进行高效操作的流对象。本质其实就是基于字节流读取时,去查了指定的码表。 字节流和字符流的区别:

    • 读写单位不同:字节流以字节(8bit)为单位,字符流以字符为单位,根据码表映射字符,一次可能读多个字节。

    • 处理对象不同:字节流能处理所有类型的数据(如图片、avi等),而字符流只能处理字符类型的数据。

    • 字节流:一次读入或读出是8位二进制。

    • 字符流:一次读入或读出是16位二进制。

    设备上的数据无论是图片或者视频,文字,它们都以二进制存储的。二进制的最终都是以一个8位为数据单元进行体现,所以计算机中的最小数据单元就是字节。意味着,字节流可以处理设备上的所有数据,所以字节流一样可以处理字符数据。

    结论:只要是处理纯文本数据,就优先考虑使用字符流。 除此之外都使用字节流。

    输入流和输出流

    输入流只能进行读操作,输出流只能进行写操作,程序中需要根据待传输数据的不同特性而使用不同的流。

    输入字节流 InputStream

    • InputStream 是所有的输入字节流的父类,它是一个抽象类。
    • ByteArrayInputStreamStringBufferInputStreamFileInputStream 是三种基本的介质流,它们分别从Byte 数组StringBuffer、和本地文件中读取数据。
    • PipedInputStream 是从与其它线程共用的管道中读取数据,与Piped 相关的知识后续单独介绍。
    • ObjectInputStream 和所有FilterInputStream 的子类都是装饰流(装饰器模式的主角)。

    输出字节流 OutputStream

    • OutputStream 是所有的输出字节流的父类,它是一个抽象类。
    • ByteArrayOutputStreamFileOutputStream 是两种基本的介质流,它们分别向Byte 数组、和本地文件中写入数据。
    • PipedOutputStream 是向与其它线程共用的管道中写入数据。
    • ObjectOutputStream 和所有FilterOutputStream 的子类都是装饰流。

    总结:

    • 输入流:InputStream或者Reader:从文件中读到程序中;
    • 输出流:OutputStream或者Writer:从程序中输出到文件中;

    节点流

    节点流:直接与数据源相连,读入或读出。
    直接使用节点流,读写不方便,为了更快的读写文件,才有了处理流。
    这里写图片描述

    常用的节点流

    • 父 类 :InputStream 、OutputStream、 Reader、 Writer
    • 文 件 :FileInputStream 、 FileOutputStrean 、FileReader 、FileWriter 文件进行处理的节点流
    • 数 组 :ByteArrayInputStream、 ByteArrayOutputStream、 CharArrayReader 、CharArrayWriter 对数组进行处理的节点流(对应的不再是文件,而是内存中的一个数组)
    • 字符串 :StringReader、 StringWriter 对字符串进行处理的节点流
    • 管 道 :PipedInputStream 、PipedOutputStream 、PipedReader 、PipedWriter 对管道进行处理的节点流

    处理流

    处理流和节点流一块使用,在节点流的基础上,再套接一层,套接在节点流上的就是处理流。如BufferedReader.处理流的构造方法总是要带一个其他的流对象做参数。一个流对象经过其他流的多次包装,称为流的链接。
    这里写图片描述

    常用的处理流

    • 缓冲流:BufferedInputStrean 、BufferedOutputStream、 BufferedReader、 BufferedWriter 增加缓冲功能,避免频繁读写硬盘。
    • 转换流:InputStreamReader 、OutputStreamReader实现字节流和字符流之间的转换。
    • 数据流: DataInputStream 、DataOutputStream 等-提供将基础数据类型写入到文件中,或者读取出来。

    转换流

    InputStreamReader 、OutputStreamWriter 要InputStreamOutputStream作为参数,实现从字节流到字符流的转换。

    构造函数

    InputStreamReader(InputStream);        //通过构造函数初始化,使用的是本系统默认的编码表GBK。
    InputStreamReader(InputStream,String charSet);   //通过该构造函数初始化,可以指定编码表。
    OutputStreamWriter(OutputStream);      //通过该构造函数初始化,使用的是本系统默认的编码表GBK。
    OutputStreamwriter(OutputStream,String charSet);   //通过该构造函数初始化,可以指定编码表。

    二:File

     Java File类的功能非常强大,利用java基本上可以对文件进行所有操作。
    首先来看File类的构造函数的源码

     /**
         * Internal constructor for already-normalized pathname strings.
         */
      private File(String pathname, int prefixLength) {
            this.path = pathname;
            this.prefixLength = prefixLength;
        }
    
        /**
         * Internal constructor for already-normalized pathname strings.
         * The parameter order is used to disambiguate this method from the
         * public(File, String) constructor.
         */
        private File(String child, File parent) {
            assert parent.path != null;
            assert (!parent.path.equals(""));
            this.path = fs.resolve(parent.path, child);
            this.prefixLength = parent.prefixLength;
        }
    
        /**
         * Creates a new <code>File</code> instance by converting the given
         * pathname string into an abstract pathname.  If the given string is
         * the empty string, then the result is the empty abstract pathname.
         *
         * @param   pathname  A pathname string
         * @throws  NullPointerException
         *          If the <code>pathname</code> argument is <code>null</code>
         */
        public File(String pathname) {
            if (pathname == null) {
                throw new NullPointerException();
            }
            this.path = fs.normalize(pathname);
            this.prefixLength = fs.prefixLength(this.path);
        }
    
     
         /**
         * @param   parent  The parent pathname string
         * @param   child   The child pathname string
         * @throws  NullPointerException
         *          If <code>child</code> is <code>null</code>
         */
        public File(String parent, String child) {
            if (child == null) {
                throw new NullPointerException();
            }
            if (parent != null && !parent.isEmpty()) {
                this.path = fs.resolve(fs.normalize(parent),
                                       fs.normalize(child));
            } else {
                this.path = fs.normalize(child);
            }
            this.prefixLength = fs.prefixLength(this.path);
        }
    
        /**
         * @param   parent  The parent abstract pathname
         * @param   child   The child pathname string
         * @throws  NullPointerException
         *          If <code>child</code> is <code>null</code>
         */
        public File(File parent, String child) {
            if (child == null) {
                throw new NullPointerException();
            }
            if (parent != null) {
                if (parent.path.equals("")) {
                    this.path = fs.resolve(fs.getDefaultParent(),
                                           fs.normalize(child));
                } else {
                    this.path = fs.resolve(parent.path,
                                           fs.normalize(child));
                }
            } else {
                this.path = fs.normalize(child);
            }
            this.prefixLength = fs.prefixLength(this.path);
        }
    
        /**
         * @param  uri
         *         An absolute, hierarchical URI with a scheme equal to
         *         <tt>"file"</tt>, a non-empty path component, and undefined
         *         authority, query, and fragment components
         *
         * @throws  NullPointerException
         *          If <tt>uri</tt> is <tt>null</tt>
         *
         * @throws  IllegalArgumentException
         *          If the preconditions on the parameter do not hold
         */
        public File(URI uri) {
    
            // Check our many preconditions
            if (!uri.isAbsolute())
                throw new IllegalArgumentException("URI is not absolute");
            if (uri.isOpaque())
                throw new IllegalArgumentException("URI is not hierarchical");
            String scheme = uri.getScheme();
            if ((scheme == null) || !scheme.equalsIgnoreCase("file"))
                throw new IllegalArgumentException("URI scheme is not "file"");
            if (uri.getAuthority() != null)
                throw new IllegalArgumentException("URI has an authority component");
            if (uri.getFragment() != null)
                throw new IllegalArgumentException("URI has a fragment component");
            if (uri.getQuery() != null)
                throw new IllegalArgumentException("URI has a query component");
            String p = uri.getPath();
            if (p.equals(""))
                throw new IllegalArgumentException("URI path component is empty");
    
            // Okay, now initialize
            p = fs.fromURIPath(p);
            if (File.separatorChar != '/')
                p = p.replace('/', File.separatorChar);
            this.path = fs.normalize(p);
            this.prefixLength = fs.prefixLength(this.path);
        }

    从源码可以看出File类的构造函数有6个,精简如下

    public File(String pathname)  //文件的绝对路径
    public File(URI uri)  //文件的URI地址
    
    public File(String parent, String child)  //指定父文件绝对路径、子文件绝对路径
    public File(File parent, String child)  //指定父文件、子文件相对路径
    
    
    //下面这两个是File类中私有的构造函数,外面不能调用
    private File(String child, File parent)  
    private File(String pathname, int prefixLength) 

      创建目录

    boolean  file.mkdir();

    如果创建成功,返回 true , 创建失败,返回false。如果这个文件夹已经存在,则返回false.
    只能创建一级目录,如果父目录不存在,返回false.

     

    创建多级目录

    boolean  file.mkdirs();

    创建多级目录,创建成功,返回true,创建失败,返回false。如果父目录不存在,就创建,并且返回true.

    创建一个新的文件

    boolean file.createNewFile();

    如果文件不存在就创建该文件,创建成功,返回 true ;创建失败,返回false。如果这个文件已经存在,则返回false.

    判断方法

    boolean file.exists() //文件是否存在
    
    boolean file.isFile() //是否是文件
    
    boolean file.isDirectory() //是否是目录
    
    boolean file.isHidden()   //是否隐藏(windows上可以设置某个文件是否隐藏)
    
    boolean file.isAbsolute() //是否为绝对路径
    
    boolean file.canRead()  //是否可读
    
    boolean file.canWrite() //是否可写
    
    boolean file.canExecute()  //是否可执行

    获取文件的信息

    String file.getName() //获取文件的名字,只是名字,没有路径
    
    String file.getParent() //获取父目录的绝对路径,返回值是一个字符串。如果文件有父目录,那么返回父目录的绝对路径,(比如:`E:cat`) , 如果文件本身就在磁盘的根目录,那么返回磁盘的路径,(比如:`E:\`)。
    
    File file.getParentFile() //获取父文件,返回值是一个File对象。
    
    long time = file.lastModified() ; //返回文件最后一次修改的时间
    Date dt = new Date(time);
    
    boolean renameTo(File file) //文件命名
    
    long file.length() //返回文件的大小,单位字节
    
    boolean file.delete() //删除文件
    
    String[] file.list() //获取该目录下的所有的文件的名字。如果`file`为文件,返回值为`null`,在使用时记得判空;但是如果`file`为目录,那么返回这个目录下所有文件的名字,只是名字,不含路径;如果`file`是一个空目录,返回一个长度为0的数组;从上面的结果可以看出,`list()` 方法,只是对`file`为目录时有效,当`file`为一个文件的时候,该方法毫无意义。
    
    File[] file.listFiles() //获取该目录下的所有的文件。如果`file`为文件,返回值为`null`,在使用时记得判空;但是如果`file`为目录,那么返回这个目录下所有的文件 ;如果`file`是一个空目录,返回一个长度为0的数组;从上面的结果可以看出,`listFiles()` 方法,只是对`file`为目录时有效,当`file`为一个文件的时候,该方法毫无意义。

    FileFilter

    FileFilter是io包里面的一个接口,从名字上可以看出,这个类是文件过滤功能的。
    需要重写accept方法

    static class MyFileFilter implements FileFilter {
            
    MyFileFilter(){            
    }
            
    //pathname:文件的绝对路径+ 文件名 , 比如:F:安来宁 - 难得.mp3  , 或者: F:文件夹1
    @Override
    public boolean accept(File pathname) {
        return false;
    }    
    }

    FilenameFilter

    FileFilter是io包里面的一个接口,从名字上可以看出,这个类是文件名字过滤功能的。
    需要重写里面的accept方法。

    package com.app;
    
    import java.io.File;
    import java.io.FilenameFilter;
    
    public class MyFilenameFilter implements FilenameFilter {
        //type为需要过滤的条件,比如如果type=".jpg",则只能返回后缀为jpg的文件
        private String type;           
        MyFilenameFilter( String type){
            this.type = type ;
        }
    
        @Override
        public boolean accept(File dir, String name) {
            //dir表示文件的当前目录,name表示文件名;
            return name.endsWith( type ) ;
        }
    
    }

    三:缓冲流-BufferedInputStream、BufferedOutputStream

    InputStream
    |__FilterInputStream
            |__BufferedInputStream

    首先抛出一个问题,有了InputStream为什么还要有BufferedInputStream?

    BufferedInputStreamBufferedOutputStream这两个类分别是FilterInputStreamFilterOutputStream的子类,作为装饰器子类,使用它们可以防止每次读取/发送数据时进行实际的写操作,代表着使用缓冲区。

    我们有必要知道不带缓冲的操作,每读一个字节就要写入一个字节,由于涉及磁盘的IO操作相比内存的操作要慢很多,所以不带缓冲的流效率很低。带缓冲的流,可以一次读很多字节,但不向磁盘中写入,只是先放到内存里。等凑够了缓冲区大小的时候一次性写入磁盘,这种方式可以减少磁盘操作次数,速度就会提高很多!

    同时正因为它们实现了缓冲功能,所以要注意在使用BufferedOutputStream写完数据后,要调用flush()方法或close()方法,强行将缓冲区中的数据写出。否则可能无法写出数据。与之相似还BufferedReaderBufferedWriter两个类。

    现在就可以回答在本文的开头提出的问题:

    BufferedInputStreamBufferedOutputStream类就是实现了缓冲功能的输入流/输出流。使用带缓冲的输入输出流,效率更高,速度更快。

    总结:

    • BufferedInputStream 是缓冲输入流。它继承于FilterInputStream

    • BufferedInputStream 的作用是为另一个输入流添加一些功能,例如,提供“缓冲功能”以及支持mark()标记reset()重置方法

    • BufferedInputStream 本质上是通过一个内部缓冲区数组实现的。例如,在新建某输入流对应的BufferedInputStream后,当我们通过read()读取输入流的数据时,BufferedInputStream会将该输入流的数据分批的填入到缓冲区中。每当缓冲区中的数据被读完之后,输入流会再次填充数据缓冲区;如此反复,直到我们读完输入流数据位置。

    BufferedInputStream API简介

    源码关键字段分析

    private static int defaultBufferSize = 8192;//内置缓存字节数组的大小 8KB
        
    protected volatile byte buf[];    //内置缓存字节数组
        
    protected int count;    //当前buf中的字节总数、注意不是底层字节输入流的源中字节总数
        
    protected int pos;        //当前buf中下一个被读取的字节下标
        
    protected int markpos = -1;    //最后一次调用mark(int readLimit)方法记录的buf中下一个被读取的字节的位置
        
    protected int marklimit;    //调用mark后、在后续调用reset()方法失败之前云寻的从in中读取的最大数据量、用于限制被标记后buffer的最大值

    构造函数

    BufferedInputStream(InputStream in) //使用默认buf大小、底层字节输入流构建bis 
    
    BufferedInputStream(InputStream in, int size) //使用指定buf大小、底层字节输入流构建bis  

    一般方法介绍

    int available();  //返回底层流对应的源中有效可供读取的字节数      
      
    void close();  //关闭此流、释放与此流有关的所有资源  
      
    boolean markSupport();  //查看此流是否支持mark
      
    void mark(int readLimit); //标记当前buf中读取下一个字节的下标  
      
    int read();  //读取buf中下一个字节  
      
    int read(byte[] b, int off, int len);  //读取buf中下一个字节  
      
    void reset();   //重置最后一次调用mark标记的buf中的位子  
      
    long skip(long n);  //跳过n个字节、 不仅仅是buf中的有效字节、也包括in的源中的字节 

    BufferedOutputStream API简介

    关键字段

    protected byte[] buf;   //内置缓存字节数组、用于存放程序要写入out的字节  
      
    protected int count;   //内置缓存字节数组中现有字节总数 

    构造函数

    BufferedOutputStream(OutputStream out); //使用默认大小、底层字节输出流构造bos。默认缓冲大小是 8192 字节( 8KB )
      
    BufferedOutputStream(OutputStream out, int size);  //使用指定大小、底层字节输出流构造bos  

    构造函数源码:

    /**
      * Creates a new buffered output stream to write data to the
      * specified underlying output stream.
      * @param   out   the underlying output stream.
      */
     public BufferedOutputStream(OutputStream out) {
         this(out, 8192);
     }
    
     /**
      * Creates a new buffered output stream to write data to the
      * specified underlying output stream with the specified buffer
      * size.
      *
      * @param   out    the underlying output stream.
      * @param   size   the buffer size.
      * @exception IllegalArgumentException if size &lt;= 0.
      */
     public BufferedOutputStream(OutputStream out, int size) {
         super(out);
         if (size <= 0) {
             throw new IllegalArgumentException("Buffer size <= 0");
         }
         buf = new byte[size];
     }

    一般方法

    //在这里提一句,`BufferedOutputStream`没有自己的`close`方法,当他调用父类`FilterOutputStrem`的方法关闭时,会间接调用自己实现的`flush`方法将buf中残存的字节flush到out中,再`out.flush()`到目的地中,DataOutputStream也是如此。 
      
    void  flush();  将写入bos中的数据flush到out指定的目的地中、注意这里不是flush到out中、因为其内部又调用了out.flush()  
      
    write(byte b);      将一个字节写入到buf中  
      
    write(byte[] b, int off, int len);      将b的一部分写入buf中 

    那么什么时候flush()才有效呢?
    答案是:当OutputStream是BufferedOutputStream时。

    当写文件需要flush()的效果时,需要
    FileOutputStream fos = new FileOutputStream(“c:a.txt”);
    BufferedOutputStream bos = new BufferedOutputStream(fos);
    也就是说,需要将FileOutputStream作为BufferedOutputStream构造函数的参数传入,然后对BufferedOutputStream进行写入操作,才能利用缓冲及flush()。

    查看BufferedOutputStream的源代码,发现所谓的buffer其实就是一个byte[]。
    BufferedOutputStream的每一次write其实是将内容写入byte[],当buffer容量到达上限时,会触发真正的磁盘写入。
    而另一种触发磁盘写入的办法就是调用flush()了。

    1.BufferedOutputStreamclose()时会自动flush
    2.BufferedOutputStream在不调用close()的情况下,缓冲区不满,又需要把缓冲区的内容写入到文件或通过网络发送到别的机器时,才需要调用flush.

    close()方法的作用
    1、关闭输入流,并且释放系统资源
    2、BufferedInputStream装饰一个 InputStream 使之具有缓冲功能,is要关闭只需要调用最终被装饰出的对象的 close()方法即可,因为它最终会调用真正数据源对象的 close()方法。因此,可以只调用外层流的close方法关闭其装饰的内层流。

    那么如果我们想逐个关闭流,我们该怎么做?

    答案是:先关闭外层流,再关闭内层流。一般情况下是:先打开的后关闭,后打开的先关闭;另一种情况:看依赖关系,如果流a依赖流b,应该先关闭流a,再关闭流b。例如处理流a依赖节点流b,应该先关闭处理流a,再关闭节点流b

    看懂了怎么正确的关闭流之后,那么我们就可以优化上面的代码了,只关闭外层的处理流。

    四:缓冲流-BufferedReader、BufferedWriter

    类的继承关系

    Reader
    |__ BufferedReader、StringReader、InputStreamReader
                                          |__ FileReader
    Writer
    |__ BufferedWriter、StringWriter、OutputStreamWriter
                                          |__ FileWriter

    BufferedReader

    . 构造函数

    BufferedReader(Reader in, int sz) //创建一个使用指定大小输入缓冲区的缓冲字符输入流。 
    
    BufferedReader(Reader in) //创建一个使用默认大小输入缓冲区的缓冲字符输入流。

    . 方法

    int  read()  //读取单个字符。
    int  read(char[] cbuf, int off, int len)  //将字符读入数组的某一部分。
    String  readLine()  //读取一个文本行。
    boolean     ready()  //判断此流是否已准备好被读取。
    void  reset()  //将流重置到最新的标记。
    long  skip(long n)  //跳过字符。
    void  close() //关闭该流并释放与之关联的所有资源。
    void  mark(int readAheadLimit) //标记流中的当前位置。
    boolean  markSupported() //判断此流是否支持 mark() 操作(它一定支持)。

    BufferedWriter

    . 构造函数

    BufferedWriter(Writer out, int sz) //创建一个使用给定大小输出缓冲区的新缓冲字符输出流。
    
    BufferedWriter(Writer out) //建一个使用默认大小输出缓冲区的缓冲字符输出流。

    . 方法

    void  close()  // 关闭此流,但要先刷新它。
    void  flush()  //刷新该流的缓冲。
    void  newLine() //写入一个行分隔符。
    void  write(char[] cbuf, int off, int len) //写入字符数组的某一部分。
    void  write(int c) //写入单个字符。
    void  write(String s, int off, int len) //写入字符串的某一部分。

    五:转换流-InputStreamReader、OutputStreamWriter

    类的继承关系

    Reader
    |__ BufferedReader、StringReader、InputStreamReader
                                          |__ FileReader
    Writer
    |__ BufferedWriter、StringWriter、OutputStreamWriter
                                          |__ FileWriter

    InputStreamReader简介

    InputStreamReader 是字符流Reader的子类,是字节流通向字符流的桥梁。你可以在构造器重指定编码的方式,如果不指定的话将采用底层操作系统的默认编码方式,例如 GBK 等。要启用从字节到字符的有效转换,可以提前从底层流读取更多的字节,使其超过满足当前读取操作所需的字节。一次只读一个字符。

    . InputStreamReader构造函数

    InputStreamReader(Inputstream  in) //创建一个使用默认字符集的 InputStreamReader。
    
    InputStreamReader(Inputstream  in,Charset cs) //创建使用给定字符集的 InputStreamReader。
    
    InputStreamReader(InputStream in, CharsetDecoder dec) //创建使用给定字符集解码器的 InputStreamReader。
    
    InputStreamReader(InputStream in, String charsetName)  //创建使用指定字符集的 InputStreamReader。

    .  一般方法

    void  close() // 关闭该流并释放与之关联的所有资源。
    
    String    getEncoding() //返回此流使用的字符编码的名称。
    
    int     read()  //读取单个字符。
    
    int     read(char[] cbuf, int offset, int length) //将字符读入数组中的某一部分。
    
    boolean  ready() //判断此流是否已经准备好用于读取。

    OutputStreamWriter简介

    OutputStreamWriter 是字符流Writer的子类,是字符流通向字节流的桥梁。每次调用 write()方法都会导致在给定字符(或字符集)上调用编码转换器。在写入底层输出流之前,得到的这些字节将在缓冲区中累积。一次只写一个字符。

    . OutputStreamWriter构造函数

    OutputStreamWriter(OutputStream out) //创建使用默认字符编码的 OutputStreamWriter
    
    OutputStreamWriter(OutputStream out, String charsetName) //创建使用指定字符集的 OutputStreamWriter。
    
    OutputStreamWriter(OutputStream out, Charset cs) //创建使用给定字符集的 OutputStreamWriter。
    
    OutputStreamWriter(OutputStream out, CharsetEncoder enc) //创建使用给定字符集编码器的 OutputStreamWriter。

    .  一般方法

    void  write(int c)   //写入的字符长度
    
    void  write(char cbuf[])  //写入的字符数组
    
    void  write(String str)  //写入的字符串
    
    void  write(String str, int off, int len)  //应该写入的字符串,开始写入的索引位置,写入的长度
    
    void  close() //关闭该流并释放与之关联的所有资源。

    需要注意的事项

    InputStreamReaderOutputStreamWriter实现从字节流到字符流之间的转换,使得流的处理效率得到提升,但是如果我们想要达到最大的效率,我们应该考虑使用缓冲字符流包装转换流的思路来解决问题。比如:

    BufferedReader in = new BufferedReader(new InputStreamReader(System.in));

    六:ByteArrayInputStream、ByteArrayOutputStream

    类的继承关系

    InputStream
    |__ ByteArrayInputStream
    OutputStream
    |__ ByteArrayOutputStream

    ByteArrayInputStream 可以将字节数组转化为输入流 。
    ByteArrayOutputStream可以捕获内存缓冲区的数据,转换成字节数组。

    ByteArrayInputStream

    . 构造函数

    public ByteArrayInputStream(byte buf[])
    
    public ByteArrayInputStream(byte buf[], int offset, int length)

    . 一般方法

    void  close() // 关闭该流并释放与之关联的所有资源。
    
    String    getEncoding() //返回此流使用的字符编码的名称。
    
    int     read()  //读取单个字符。
    
    int     read(char[] cbuf, int offset, int length) //将字符读入数组中的某一部分。
    
    boolean  ready() //判断此流是否已经准备好用于读取。

    ByteArrayOutputStream

    . 构造函数

    public ByteArrayOutputStream()
    
    public ByteArrayOutputStream(int size)

    . 一般方法

    void write(int b)
    
    void write(byte b[], int off, int len)
    
    void writeTo(OutputStream out)
    
    byte toByteArray()[]
    
    void close()

    七:Commons IO 2.5-FileUtils

    Commons IO简介

    FileUtils 文件操作工具类

    . 复制文件夹

    //复制文件夹(文件夹里面的文件内容也会复制),file1和file2平级。
    //参数1:文件夹; 参数2:文件夹
    void copyDirectory( file1 , file2 );  
    
    //复制文件夹到另一个文件夹。 file1是file2的子文件夹.
    //参数1:文件夹; 参数2:文件夹
    void copyDirectoryToDirectory( file1 , file2 );
    
    //复制文件夹,带有文件过滤功能
    void copyDirectory(File srcDir, File destDir, FileFilter filter)

    .  复制文件

    void copyFile(final File srcFile, final File destFile) //复制文件到另外一个文件
    
    void long copyFile(final File input, final OutputStream output) //复制文件到输出流
    
    void copyFileToDirectory( file1 , file2)  //复制文件到一个指定的目录
    
    //把输入流里面的内容复制到指定文件
    void copyInputStreamToFile( InputStream source, File destination)
    
    //把URL 里面内容复制到文件。可以下载文件。
    //参数1:URL资源 ; 参数2:目标文件
    void copyURLToFile(final URL source, final File destination)
    
    //把URL 里面内容复制到文件。可以下载文件。
    //参数1:URL资源 ; 参数2:目标文件;参数3:http连接超时时间 ; 参数4:读取超时时间
    void copyURLToFile(final URL source, final File destination,
                                         final int connectionTimeout, final int readTimeout)

    . 下载文件

    copyURLToFile(final URL source, final File destination)

    . 把字符串写入文件

    void writeStringToFile(final File file, final String data, final String encoding)
    
    //参数1:需要写入的文件,如果文件不存在,将自动创建。  参数2:需要写入的内容
    //参数3:编码格式     参数4:是否为追加模式( ture: 追加模式,把字符串追加到原内容后面)
    void writeStringToFile(final File file, final String data, final Charset encoding, final boolean
                append)

    . 把字节数组写入文件

    //File:目标文件
    //byte[]: 字节数组
    //boolean append : 是否为追加模式
    //final int off: 数组开始写入的位置 ; final int len :写入的长度
    
    void writeByteArrayToFile(final File file, final byte[] data)
    
    void writeByteArrayToFile(final File file, final byte[] data, final boolean append)
    
    void writeByteArrayToFile(final File file, final byte[] data, final int off, final int len)
    
    void writeByteArrayToFile(final File file, final byte[] data, final int off, final int len,
                                                final boolean append)

    . 把集合里面的内容写入文件

    //File file: 目标文件
    //Collection<?> lines: 内容集合
    //boolean append : 是否为追加模式
    //String encoding : 编码方式,比如"UTF-8" 
    //String lineEnding : 每一行以什么结尾
    void writeLines(final File file, final Collection<?> lines)
    
    void writeLines(final File file, final Collection<?> lines, final boolean append)
    
    void writeLines(final File file, final String encoding, final Collection<?> lines)
    
    void writeLines(final File file, final String encoding, final Collection<?> lines,
                                      final boolean append)
                                      
    void writeLines(final File file, final String encoding, final Collection<?> lines,
                                      final String lineEnding)
    
    void writeLines(final File file, final String encoding, final Collection<?> lines,
                                      final String lineEnding, final boolean append)
    
    void writeLines(final File file, final Collection<?> lines, final String lineEnding)
    
    void writeLines(final File file, final Collection<?> lines, final String lineEnding,
                                      final boolean append)

    . 往文件里面写内容

    /**
    * 参数解释
    * File file:目标文件
    * CharSequence data : 要写入的内容
    * Charset encoding;String encoding : 编码格式
    * boolean append:是否为追加模式
    */
    
    void write(final File file, final CharSequence data, final Charset encoding)
    
    void write(final File file, final CharSequence data, final String encoding)
    
    void write(final File file, final CharSequence data, final Charset encoding, final boolean append)
    
    void write(final File file, final CharSequence data, final String encoding, final boolean append)

    . 文件移动

    /文件夹移动,文件夹在内的所有文件都将移动 
    void moveDirectory(final File srcDir, final File destDir)
    
    //文件夹移动到另外一个文件内部。boolean createDestDir:如果destDir文件夹不存在,是否要创建一个
    void moveDirectoryToDirectory(final File src, final File destDir, final boolean createDestDir)
    
    //移动文件
    void moveFile(final File srcFile, final File destFile)
    
    //把文件移动到另外一个文件内部。boolean createDestDir:如果destDir文件夹不存在,是否要创建一个
    void moveFileToDirectory(final File srcFile, final File destDir, final boolean createDestDir)
    
    //移动文件或者目录到指定的文件夹内。
    //boolean createDestDir:如果destDir文件夹不存在,是否要创建一个
    void moveToDirectory(final File src, final File destDir, final boolean createDestDir)

    . 清空和删除文件夹

    //删除一个文件夹,包括文件夹和文件夹里面所有的文件
    void deleteDirectory(final File directory)
    
    //清空一个文件夹里面的所有的内容
    void cleanDirectory(final File directory)
    
    //删除一个文件,会抛出异常
    //如果file是文件夹,就删除文件夹及文件夹里面所有的内容。如果file是文件,就删除。
    //如果某个文件/文件夹由于某些原因无法被删除,会抛出异常
    void forceDelete(final File file)  
    
    //删除一个文件,没有任何异常抛出
    //如果file是文件夹,就删除文件夹及文件夹里面所有的内容。如果file是文件,就删除。
    //如果某个文件/文件夹由于某些原因无法被删除,不会抛出任何异常
    boolean deleteQuietly(final File file) 

    . 创建文件夹

    //创建一个文件夹,如果由于某些原因导致不能创建,则抛出异常
    //一次可以创建单级或者多级目录
    void forceMkdir(final File directory)
    
    //创建文件的父级目录
    void forceMkdirParent(final File file)

    . 文件获取输入/输出流

    //获取输入流
    FileInputStream openInputStream(final File file)
    
    //获取输出流
    FileOutputStream openOutputStream(final File file)

    . 读取文件

    //把文件读取到字节数组里面
    byte[] readFileToByteArray(final File file)
    
    //把文件读取成字符串 ;Charset encoding:编码格式
    String readFileToString(final File file, final Charset encoding)
    
    //把文件读取成字符串 ;String encoding:编码格式
    String readFileToString(final File file, final String encoding)
    
    //把文件读取成字符串集合 ;Charset encoding:编码格式
    List<String> readLines(final File file, final Charset encoding)
    
    //把文件读取成字符串集合 ;String encoding:编码格式
    List<String> readLines(final File file, final String encoding)

    .  测试两个文件的修改时间那个比较新/老

    //判断file文件的修改是否比reference文件新
    boolean isFileNewer(final File file, final File reference) 
    
    //判断file文件的修改是否比 date日期新
    boolean isFileNewer(final File file, final Date date)
    
    //判断file文件的修改是否比 timeMillis 毫秒值新
    boolean isFileNewer(final File file, final long timeMillis) 
    
    //判断file文件的修改是否比reference文件老
    boolean isFileOlder(final File file, final File reference)
    
    //判断file文件的修改是否比 date日期老
    boolean isFileOlder(final File file, final Date date)
    
    //判断file文件的修改是否比 timeMillis 毫秒值老
    boolean isFileOlder(final File file, final long timeMillis)

    .  其他

    /判断文件夹内是否包含某个文件或者文件夹
    boolean directoryContains(final File directory, final File child)
    
    //获取文件或者文件夹的大小
    long sizeOf(final File file) 
    
    //获取临时目录文件
    File getTempDirectory()
    
    //获取临时目录路径
    String getTempDirectoryPath() 
    
    //获取用户目录文件  
    File getUserDirectory()
    
    //获取用户目录路径  
    static String getUserDirectoryPath()
    
    //如果不存在,新建文件或者创建单级目录或者多级目录    
    //如果存在,修改文件修改时间   
    void touch(final File file)
    
    //比较两个文件内容是否相同
    boolean contentEquals(final File file1, final File file2)

    转载:http://blog.csdn.net/zhaoyanjun6/article/details/54292148
    本文出自【赵彦军的博客】

  • 相关阅读:
    Java内存模型总结
    SpringMVC流程源码分析及DispatcherServlet核心源码
    算法学习之剑指offer(十二)
    算法学习之剑指offer(十一)
    为什么局部内部类和匿名内部类只能访问 final 的局部变量?
    Java 中序列化与反序列化
    SpringBoot 上传文件突然报错 Failed to parse multipart servlet request; nested exception is java.io.IOException: The temporary upload location [/tmp/tomcat.1428942566812653608
    不能往Windows Server 2008 R2 Server中复制文件的解决方法
    Java 设计模式之单例模式
    Java 设计模式之抽象工厂模式
  • 原文地址:https://www.cnblogs.com/sfnz/p/14288837.html
Copyright © 2011-2022 走看看