zoukankan      html  css  js  c++  java
  • java字符流操作flush()方法及其注意事项

    java字符流操作flush()方法及其注意事项

     

    flush()方法介绍

    查阅文档可以发现,IO流中每一个类都实现了Closeable接口,它们进行资源操作之后都需要执行close()方法将流关闭 。但字节流与字符流的不同之处在于:字节流是直接与数据产生交互,而字符流在与数据交互之前要经过一个缓冲区 。 
    草图: 
    这里写图片描述

    使用字符流对资源进行操作的时候,如果不使用close()方法,则读取的数据将保存在缓冲区中,要清空缓冲区中的数据有两种办法:

    • public abstract void close() throws IOException 
      关闭流的同时将清空缓冲区中的数据,该抽象方法由具体的子类实现
    • public abstract void flush() throws IOException 
      不关闭流的话,使用此方法可以清空缓冲区中的数据,但要注意的是,此方法只有Writer类或其子类拥有,而在Reader类中并没有提供。此方法同样是在具体的子类中进行实现 。
    public class Writer_Flush_Test {
        public static void main(String[] args) throws IOException {
            File file = new File("D:" + File.separator + "IOTest" + File.separator + "newFile.txt");
            if (!file.getParentFile().exists()) {
                file.getParentFile().mkdirs();
            }
            Writer w = new FileWriter(file, true);
            w.flush();
            w.write("@@@这是测试flush方法的字符串***
    ");
        }
    }
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11

    结果可以发现,清空了缓冲区中的数据再向文件中写入时,数据写不进去 。 
    这里写图片描述

    flush()使用注意事项

    修改以上代码,当清空缓冲区,再写入之后,如果再执行close()关闭流的方法,数据将正常写入 。

    public class Writer_Flush_Test {
        public static void main(String[] args) throws IOException {
            File file = new File("D:" + File.separator + "IOTest" + File.separator + "newFile.txt");
            if (!file.getParentFile().exists()) {
                file.getParentFile().mkdirs();
            }
            Writer w = new FileWriter(file, true);
            w.flush(); 
            w.write("@@@这是测试flush方法的字符串***
    ");
            // 执行之前操作之后使用close()关闭流 
            w.close();
        }

    微信公众号【黄小斜】大厂程序员,互联网行业新知,终身学习践行者。关注后回复「Java」、「Python」、「C++」、「大数据」、「机器学习」、「算法」、「AI」、「Android」、「前端」、「iOS」、「考研」、「BAT」、「校招」、「笔试」、「面试」、「面经」、「计算机基础」、「LeetCode」 等关键字可以获取对应的免费学习资料。 

                         

    可以发现此时正常写入文件中 。具体原因未知,希望明白的朋友告知,但就目前来看,要做的是一定要避免这样的错误 。

  • 相关阅读:
    Is It A Tree?(并查集)(dfs也可以解决)
    【转】python中查询某个函数的使用方法
    python2和python3 print输出不换行
    Python在Windows下列出所有的安装包和模块
    构建打包发布模块及导入使用
    Python保存时提示“SyntaxError: Non-ASCII character 'xe8' in file”
    python基础学习(一)
    命令别名设定:alias,unalias 历史命令:history
    变量内容的删除、取代与替换(optional)
    变量键盘读取、数组与宣告:read,array,declare
  • 原文地址:https://www.cnblogs.com/xll1025/p/6424528.html
Copyright © 2011-2022 走看看