FileWriter学习

时间:2015-01-31 20:38:24   收藏:0   阅读:152


FileWriter 文件输出流是用于将数据写入 FileFileDescriptor 的输出流。文件是否可用或能否可以被创建取决于基础平台。特别是某些平台一次只允许一个FileOutputStream(或其他文件写入对象)打开文件进行写入。在这种情况下,如果所涉及的文件已经打开,则此类中的构造方法将失败。

FileOutputStream 用于写入诸如图像数据之类的原始字节的流。要写入字符流,请考虑使用 FileWriter


共有五个构造方法

其中方法可以分为三组,入参带File的为一组,入参带String 的为一组,这两组方法基本相似。


带File 的构造方法是直接传入文件来构造FileWriter对象,而带String 的构造方法,则必须先通过new File(String path) 来构造File 文件,再来构造FileWriter对象。

查看java源码

    /**
     * Constructs a FileWriter object given a file name.
     *
     * @param fileName  String The system-dependent filename.
     * @throws IOException  if the named file exists but is a directory rather
     *                  than a regular file, does not exist but cannot be
     *                  created, or cannot be opened for any other reason
     */
    public FileWriter(String fileName) throws IOException {
        super(new FileOutputStream(fileName));
    }

    /**
     * Constructs a FileWriter object given a File object.
     *
     * @param file  a File object to write to.
     * @throws IOException  if the file exists but is a directory rather than
     *                  a regular file, does not exist but cannot be created,
     *                  or cannot be opened for any other reason
     */
    public FileWriter(File file) throws IOException {
        super(new FileOutputStream(file));
    }

跟踪FileOutputStream 源码查看FileOutputStream 的构造方法

    /**
     * 创建一个向具有指定名称的文件中写入数据的输出文件流
     * 省略大段注释 
     */ 
    public FileOutputStream(String name) throws FileNotFoundException { 
        this(name != null ? new File(name) : null, false); 
    } 

     /** 
      * 创建一个向指定<code>File</code> 对象表示的文件中写入数据的文件输出流
      * 省略大段注释 
      */ 
     public FileOutputStream(File file) throws FileNotFoundException { 
         this(file, false);
     }


给定File file做入参的方法和给定String name 做入参的方法区别就在于给name的方法,在调用默认的构造方法前,先判断name是否为空,非空时构造File 对象出来。

再看 File file 入参的两个方法,FileWriter(File file)  和 FileWriter(File file, boolean append) 的区别在于后面多了一个boolean append 参数

boolean append 的作用是什么呢?查看

    /**
     * 省略大段注释
     * @param      file               the file to be opened for writing.
     * @param     append      if true , then bytes will be written
     *                   to the end of the file rather than the beginning
     */
    public FileOutputStream(File file, boolean append)
        throws FileNotFoundException
    {
        //  省略大段代码
    }
append  如果为 true,则将字节写入文件末尾处,而不是写入文件开始处

append 相当于指定了写入的方式,是覆盖写还是追加写

append 为true时,追加写,相当于Linux 里面的 >> 操作符;append 为false时,覆盖写,相当于Linux 里面的 > 操作符。


FileWriter(FileDescriptor fd)  类,暂未用过,这里就不细谈了。



评论(0
© 2014 mamicode.com 版权所有 京ICP备13008772号-2  联系我们:gaon5@hotmail.com
迷上了代码!