zoukankan      html  css  js  c++  java
  • 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

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

  • 相关阅读:
    Python-发送邮件
    Python基础-类的继承
    Python基础-列表推导式
    三、Linux下mysql的完整安装
    二、linux下apache2.2.11+php5.6.3的环境配置
    linux下编译安装php各种报错大集合
    一、linux下nginx1.7.8+php5.6.3的环境配置
    linux ./configure 的参数详解
    div随窗口变化设置高度
    在地图上增加标注点并为每个点增加各自的信息窗口
  • 原文地址:https://www.cnblogs.com/wwjj4811/p/14688283.html
Copyright © 2011-2022 走看看