1.前置知识:字符集
简介
使用ASCII码表示128个字符,第一位都是0。
GBK:一个中文字符编码成两个字节存储。包含ASCII,汉字第一个字节第一位必须是1,以此来区分是汉字还是字母或者其他。
Unicode:万国码。
UTF-32:四个字节表示一个字符。
UTF-8:可变长编码方案。一到四个字不等。ASCII占一个字节,汉字占三个字节
字符集的编码与解码
2.IO流
概述
输入流和输出流。
(1)字节输入流 InputStream FileInputStream 从磁盘读内容到内存
(2)字节输出流 OutStream FileOutStream
(3)字符输入流 Reader FileReader
(4)字符输出流 Writer FileWriter
以上四个都是抽象类,后面是他们的实现类。
(1)FileInputStream 文件字节输入流(读一个字节)
上面代码有很多去缺陷。1.读取性能很差,因为这是到硬盘去读,效率低。2.读取汉字会乱码。
流使用之后需要关闭。
(2)读取多个字节
上面代码读取性能的搭配提升,但读取汉字也会出现问题,会出现乱码。
(3)一次性读完全部字节
可以解决中文乱码的问题,适合读相对较较小的文件。如果文件过大,创建的字节数组也会过大,会引起内存溢出。
读取文本内容更适合用字符流。
字节流适合做数据的转移,如文件复制。
(4)文件字节输出流
把内存的数据以字节的形式写到文件中去。
案例:文件复制
一切文件的复制,不会出错,虽然读的时候是分开读的,但是传输完成会接着读,只要编码合适就能成功显示。
释放资源的方式
前面学的close方法关闭通道会出现问题,比如程序异常了,就不会执行后边的程序,通道关不上。下面这两种是解决方法。
(1)try-catch-finally
finally代码区的特点:无论try的程序是否正常执行了,还是出现了异常,最后一定会执行finally的代码,除非jvm终止,加return也没用。
注意:在finally不要加return语句。
finally作用:一般用于执行完程序释放资源。
(2)try-with-resource
更简单的资源释放方案。
try这里只能放资源,int a = 1;会报错
资源是实现了AutoCloseable接口的对象,在try语句块结束时自动调用close()方法释放资源
也可以自己写一个类实现AutoCloseable接口,在try语句块结束时自动调用close()方法释放资源