105.Java中IO流_字符流拷贝文件

字符流拷贝文件

一个文本文件中有中文有英文字母,有数字。想要把这个文件拷贝到别的目录中。

我们可以使用字节流进行拷贝,使用字符流呢?肯定也是可以的。、

1.1.   字符流拷贝文件实现1

public static void main(String[] args) throws Exception {
        String path1 = "c:/a.txt";
        String path2 = "c:/b.txt";

        copyFile(path1, path2);
    }

/**
     * 使用字符流拷贝文件
     */
    public static void copyFile(String path1, String path2) throws Exception {
        Reader reader = new FileReader(path1);
        Writer writer = new FileWriter(path2);

        int ch = -1;
        while ((ch = reader.read()) != -1) {
            writer.write(ch);
        }

        reader.close();
        writer.close();
    }

但是这个一次读一个字符就写一个字符,效率不高。把读到的字符放到字符数组中,再一次性的写出。

1.2.   字符流拷贝文件实现2

public static void main(String[] args) throws Exception {
        String path1 = "c:/a.txt";
        String path2 = "c:/b.txt";

        copyFile(path1, path2);
    }

public static void copyFile3(String path1, String path2) throws Exception {
        Reader reader = new FileReader(path1);
        Writer writer = new FileWriter(path2);

        int ch = -1;
        char [] arr=new char[1024];
        while ((ch = reader.read(arr)) != -1) {
            writer.write(arr,0,ch);
        }

        reader.close();
        writer.close();
    }

字节流可以拷贝视频和音频等文件,那么字符流可以拷贝这些吗?

经过验证拷贝图片是不行的。发现丢失了信息,为什么呢?

计算机中的所有信息都是以二进制形式进行的存储(1010)图片中的也都是二进制

在读取文件的时候字符流自动对这些二进制按照码表进行了编码处理,但是图片本来就是二进制文件,不需要进行编码。有一些巧合在码表中有对应,就可以处理,并不是所有的二进制都可以找到对应的。信息就会丢失。所以字符流只能拷贝以字符为单位的文本文件

(以ASCII码为例是127个,并不是所有的二进制都可以找到对应的ASCII,有些对不上的,就会丢失信息。)

author@nohert
原文地址:https://www.cnblogs.com/gzgBlog/p/13624615.html