之前介绍了字节流和字符流,本篇文章关于字节流和字符流想到哪就写到哪当作前两篇文章的补充。
- 字节(Byte )是计算机信息技术用于计量存储容量的一种计量单位,作为一个单位来处理的一个二进制数字串,是构成信息的一个小单位。最常用的字节是八位的字节,即它包含八位的二进制数。1byte = 8bit即1字节=8位二进制。字节是最小的信息单位。
- 字符(Character)是各种文字和符号的总称,包括各国家文字、标点符号、图形符号、数字等。不同编码里,字符与字节的对应关系也不同。例如在 ASCII 编码中,一个英文字母字符存储需要1个字节。在 GBK 编码中,一个汉字字符存储需要2个字节。在UTF-8编码中,一个汉字字符储存需要3个字节。
- 字符集(Character set)是多个字符的集合,字符集种类较多,每个字符集包含的字符个数不同,常见字符集名称:ASCII字符集、GB2312字符集、BIG5字符集、 GB18030字符集、Unicode字符集等。字符集可以看作就是一种将二进制与字符对应起来的规范,字符集不同即二进制与字符对应规则不同。
- 由于硬盘上所有文件都是以字节形式存在的,因此字节流可以操作文本,图片,视频等一切资源;字符流只能对文本进行操作。
- 字节流直接对文件本身进行操作,字符流用到了缓冲区,因此字符流写入文件时如果不关闭流且不调用flush()方法,文件中并没有写入内容。调用flush()方法强制将缓冲区中的内容写入到文件中或者调用close()方法关闭流才会真正写入。
- 下面的程序为了验证使用缓冲区后的字节流和字符流效率更高,字符流比字节流效率更高。
//测试程序 public static void main(String[] args) { FileInputStream fis = null; FileOutputStream fos = null; FileReader fd = null; FileWriter fw = null; try { fis = new FileInputStream("D:\\FileInputStream\\hello.txt"); fos = new FileOutputStream("D:\\FileInputStream\\helloCopy.txt"); fd = new FileReader("D:\\FileInputStream\\hello.txt"); fw = new FileWriter("D:\\FileInputStream\\helloCopy.txt"); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } BufferedInputStream bis = new BufferedInputStream(fis); BufferedOutputStream bos = new BufferedOutputStream(fos); BufferedReader br = new BufferedReader(fd); BufferedWriter bw = new BufferedWriter(fw); try { int len; //字节流 byte[] byteArr = new byte[1024*1024*1024]; long time1 = System.currentTimeMillis(); if ((len=fis.read(byteArr))!=-1) { fos.write(byteArr,0,len); } fos.flush(); System.out.println("字节流复制文件需要:"+(System.currentTimeMillis()-time1)+"毫秒"); //使用缓冲区的字节流 long time2 = System.currentTimeMillis(); if ((len = bis.read(byteArr)) != -1) { bos.write(byteArr,0,len); } bos.flush(); System.out.println("使用缓冲区的字节流复制文件需要:"+(System.currentTimeMillis()-time2)+"毫秒"); //字符流 char[] charArr = new char[1024*1024]; long time3 = System.currentTimeMillis(); if ((len = fd.read(charArr)) != -1) { fw.write(charArr,0,len); } fw.flush(); System.out.println("字符流复制文件需要:"+(System.currentTimeMillis()-time3)+"毫秒"); //使用缓冲区的字符流 long time4 = System.currentTimeMillis(); if ((len = br.read(charArr)) != -1) { bw.write(charArr,0,len); } bw.flush(); System.out.println("使用缓冲区的字符流复制文件需要:"+(System.currentTimeMillis()-time4)+"毫秒"); } catch (IOException e) { e.printStackTrace(); } finally { try { bw.close(); bos.close(); br.close(); bis.close(); fw.close(); fd.close(); fis.close(); fos.close(); } catch (IOException e) { e.printStackTrace(); } } } //输出结果 字节流复制文件需要:1505毫秒 使用缓冲区的字节流复制文件需要:389毫秒 字符流复制文件需要:58毫秒 使用缓冲区的字符流复制文件需要:11毫秒