• 104.Java中IO流_字符流_Writer


    Writer

    Writer中的常见的方法:

    1,write(ch): 将一个字符写入到流中。

    2,write(char[]): 将一个字符数组写入到流中。

    3,write(String): 将一个字符串写入到流中。

    4,flush():刷新流,将流中的数据刷新到目的地中,流还存在。

    5,close():关闭资源:在关闭前会先调用flush(),刷新流中的数据去目的地。然流关闭。

    发现基本方法和OutputStream 类似,有write方法,功能更多一些。可以接收字符串。

    同样道理Writer是抽象类无法创建对象。查阅API文档,找到了Writer的子类FileWriter

    1:将文本数据存储到一个文件中。

    public class IoTest2_Writer {
    
        public static void main(String[] args) throws Exception {
            String path = "c:/ab.txt";
    
            writeToFile(path);
        }
    
        /**
         * 写指定数据到指定文件中
         * 
         */
        public static void writeToFile(String path) throws Exception {
            Writer writer = new FileWriter(path);
            writer.write('中');
            writer.write("世界".toCharArray());
            writer.write("中国");
    
            writer.close();
        }
    }

    2:追加文件:

    默认的FileWriter方法新值会覆盖旧值,想要实现追加功能需要

    使用如下构造函数创建输出流 append值为true即可。

    FileWriter(String fileName, boolean append)

    FileWriter(File file, boolean append)

    3:flush方法

       如果使用字符输出流,没有调用close方法,会发生什么?

    private static void writeFileByWriter(File file) throws IOException {
            FileWriter fw = new FileWriter(file);
            fw.write('新');
    fw.flush();
            fw.write("中国".toCharArray());
            fw.write("世界你好!!!".toCharArray());
            fw.write("明天");    
            // 关闭流资源
            //fw.close();
        }

    程序执行完毕打开文件,发现没有内容写入.原来需要使用flush方法. 刷新该流的缓冲。

    为什么只要指定claose方法就不用再flush方法,因为close也调用了flush方法.

    author@nohert
  • 相关阅读:
    多个列表根据交集进行合并
    python 在cv2 基础上pillow写文字
    python 欧拉角,旋转矩阵,四元数之间转换
    python 实现循环链表
    模板,用于处理数据
    numba学习一
    centos8下使用mysql安装包安装mysql8.02
    (一)什么是Rabbitmq look
    (4)什么是Ribbon负载均衡 look
    (5)使用Nacos注册中心 look
  • 原文地址:https://www.cnblogs.com/gzgBlog/p/13624614.html
Copyright © 2020-2023  润新知