• java基础:IO流之FileReader和FileWriter


    FileReader使用

    read()

    项目根目录下有一个hello.txt

    image-20210422093512763

    FileReader的read方法:

        /**
         * Reads a single character.
         *
           读取字符,当流结束的时候,返回-1
         * @return The character read, or -1 if the end of the stream has been
         *         reached
         *
         * @exception  IOException  If an I/O error occurs
         */
        public int read() throws IOException {
            return sd.read();
        }
    

    由此我们可以写出:

        @Test
        public void test1() throws IOException {
            //实例化File类的对象,指明要操作的文件
            File file = new File("hello.txt");
            //提供具体的流
            FileReader fileReader = new FileReader(file);
            int data;
            while((data = fileReader.read()) != -1){
                System.out.print((char)data);
            }
            //关闭流
            fileReader.close();
        }
    

    image-20210422093705666

    优化上述代码:

        @Test
        public void test1(){
            //实例化File类的对象,指明要操作的文件
            File file = new File("hello.txt");
            //提供具体的流
            //读入的文件一定要存在,否则报异常
            try(FileReader fileReader = new FileReader(file)){
                int data;
                while((data = fileReader.read()) != -1){
                    System.out.print((char)data);
                }
            }catch (IOException e){
                e.printStackTrace();
            }
        }
    

    read(char cbuf[])

    将读取的字符放入到传入的数组中。返回值为int,返回每次读入到cbuf数组中的字符个数,到达文件末尾,返回-1。

    当文件很大时,效率要比无参的read方法要高。

    注意到read(char cbuf[])内部还调用了read(char cbuf[], int off, int len)方法,该方法实际工作用到可能性很小,这里不介绍。

        /**
         * Reads characters into an array.  This method will block until some input
         * is available, an I/O error occurs, or the end of the stream is reached.
         *
         * @param       cbuf  Destination buffer
         *
         * @return      The number of characters read, or -1
         *              if the end of the stream
         *              has been reached
         *
         * @exception   IOException  If an I/O error occurs
         */
        public int read(char cbuf[]) throws IOException {
            return read(cbuf, 0, cbuf.length);
        }
    

    测试:

    //实例化File类的对象,指明要操作的文件
    File file = new File("hello.txt");
    //提供具体的流,读入操作
    try(FileReader fileReader = new FileReader(file)){
        char[] cBuf = new char[5];
        int len;
        while ((len = fileReader.read(cBuf))!=-1){
            for(int i =0 ;i<len;i++){
                System.out.print(cBuf[i]);
            }
        }
    }catch (IOException e){
        e.printStackTrace();
    }
    

    改进写法:

            //实例化File类的对象,指明要操作的文件
            File file = new File("hello.txt");
            //提供具体的流,读入操作
            try(FileReader fileReader = new FileReader(file)){
                char[] cBuf = new char[5];
                int len;
                while ((len = fileReader.read(cBuf))!=-1){
                    String str = new String(cBuf, 0, len);
                    System.out.print(str);
                }
            }catch (IOException e){
                e.printStackTrace();
            }
    

    FileWriter使用

    File file = new File("hello1.txt");
    //提供FileWriter的对象,用于写出操作
    try(FileWriter fw = new FileWriter(file)){
        //写出操作
        fw.write("hello FileWriter!
    ");
        fw.write("hello world!");
    }catch (IOException e){
        e.printStackTrace();
    }
    

    image-20210422100400831

    如果使用FileWriter(File file)构造器,如果文件不存在的话,会自动创建文件;如果文件存在的话,会覆盖原来文件,写出新的内容。

    此外还有一个构造器传入boolean参数的:如果传入true,则追加到文件末尾不覆盖

        /**
         * Constructs a {@code FileWriter} given the {@code File} to write and
         * a boolean indicating whether to append the data written, using the platform's
         * {@linkplain java.nio.charset.Charset#defaultCharset() default charset}.
         *
         * @param file  the {@code File} to write
         * @param     append    if {@code true}, then bytes will be written
         *                      to the end of the file rather than the beginning
         * @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
         * @since 1.4
         */
        public FileWriter(File file, boolean append) throws IOException {
            super(new FileOutputStream(file, append));
        }
    

    测试:

    File file = new File("hello1.txt");
    //提供FileWriter的对象,用于写出操作
    try(FileWriter fw = new FileWriter(file, true)){
        //写出操作
        fw.write("hello FileWriter!
    ");
        fw.write("hello world!");
    }catch (IOException e){
        e.printStackTrace();
    }
    

    image-20210422100802198

    实现文件复制

    使用FileReader和FileWriter可以实现,代码也很简单

    File src = new File("hello1.txt");
    File dest = new File("hello2.txt");
    
    try(FileReader fr = new FileReader(src);
        FileWriter fw = new FileWriter(dest)){
    
        char[] cBuf = new char[5];
        int len;
        while ((len = fr.read(cBuf))!=-1){
            fw.write(cBuf, 0 ,len);
        }
    }catch (IOException e){
        e.printStackTrace();
    }
    

    image-20210422101430678

    字符流不能处理图片

    测试代码:

    @Test
    public void test5(){
        File src = new File("a.jpg");
        File dest = new File("b.jpg");
    
        try(FileReader fr = new FileReader(src);
            FileWriter fw = new FileWriter(dest)){
    
            char[] cBuf = new char[5];
            int len;
            while ((len = fr.read(cBuf))!=-1){
                fw.write(cBuf, 0 ,len);
            }
        }catch (IOException e){
            e.printStackTrace();
        }
    }
    

    发现生成的b.jpg打不开:

    image-20210422102052208

    所以字符流不能处理图片等字节数据。

  • 相关阅读:
    [rabbitmq] python版本(六)远程过程调用
    [rabbitmq] python版本(五) 主题交换机
    物体运动学习笔记(一)
    基于TimeLine编辑角色动画(二)
    基于TimeLine编辑角色动画(一)
    SQlite常用操作封装
    unity三种资源加载方式Resources,AssetBundle,WebRequset的同步异步加载
    场景同步异步加载
    XML保存账号密码
    unity EditorWindow 绘制时间刻度
  • 原文地址:https://www.cnblogs.com/wwjj4811/p/14688283.html
Copyright © 2020-2023  润新知