lnputStreamReader介绍&代码实现与练习_转换文件编码
InputStreamReader类:
java.io.InputStreamReader extends Reader
InputStreamReader:是字节流通向字符流的桥梁:他使用指定的charset读取字节并将其解码为字符。
继承自父类的共性成员方法:
int read() 读取单个字符并返回
int read(char[] cbuf) 一次读取多个字符,经字符读入数组中
void close() 关闭该流并释放与之关联的所有资源
构造方法:
InputStreamReader(InputStream in) 创建一个使用默认字符集的InputStreamReader
InputStreamReader(InouStream in,String charsetName) 创建使用指定字符集的 InputStreamReader
参数:
InputStream in:字节输入流,用来读取文件中保存的字节
String charsetName:指定的编码表名称,不区分大小写,可以是utf-8/UTF-8,gbk/GBK,...不指定默认使用UTF-8
使用步骤:
1.创建InputStreamReader对象,构造方法中传递字节输入流和指定的编码表名称
2.使用InputStreamReader对象中的方法read读取文件
3.释放资源。
注意事项:
构造方法中指定的编码表名称要和文件的编码相同,否则会发生乱码
public class Demo03InputStreamReader { public static void main(String[] args) throws IOException { // read_utf_8(); read_gbk(); } /* 使用InputStreamReader读取GBK格式的文件 */ private static void read_gbk() throws IOException { //1.创建InputStreamReader对象,构造方法中传递字节输入流和指定的编码表名称 InputStreamReader isr = new InputStreamReader(new FileInputStream("day10_IO\\gbk.txt"),"GBK"); //2.使用InputStreamReader对象中的方法read读取文件 int len = 0; while((len = isr.read()) != -1){ System.out.println((char)len); } //3.释放资源。 isr.close(); } /* 使用InputStreamReader读取UTF-8格式的文件 */ private static void read_utf_8() throws IOException { //1.创建InputStreamReader对象,构造方法中传递字节输入流和指定的编码表名称 InputStreamReader isr = new InputStreamReader(new FileInputStream("day10_IO\\utf_8.txt"),"UTF-8"); //2.使用InputStreamReader对象中的方法read读取文件 int len = 0; while((len = isr.read()) != -1){ System.out.println((char)len); } //3.释放资源。 isr.close(); } }
练习——转换编码
将GBK编码的文本文件,转换UTF-8编码文档文件
案例分析
指定GBK编码的转换流,读取文件
指定UTF-8编码的转换流,读取文件
package DemoThreadPool; import java.io.*; /** * 练习:转换文件编码 * 将GBK编码的文本文件,转换为UTF-8编码的文本文件。分析: * 1.创建InputStreamReader对象,构造方法中传递字节输入流和指定的编码表名称GBK * 2.创建outputStreamiriter对象,构造方法中传递字节输出流和指定的编码表挡称UTF-8 * 3.使用InputstreamReader对象中的方法read读取文件 * 4.使用outputstreamwriter对象中的方法vrite,把读取的数据写入到文件中 * 5 .释放资源 */ public class Demo04_Test { public static void main(String[] args) throws IOException { //1.创建InputStreamReader对象,构造方法中传递字节输入流和指定的编码表名称GBK InputStreamReader isr = new InputStreamReader(new FileInputStream("G:\\xiangmu\\jichu\\wenjianjia\\a.txt"), "GBK"); //2.创建outputStreamiriter对象,构造方法中传递字节输出流和指定的编码表挡称UTF-8 OutputStreamWriter ois = new OutputStreamWriter(new FileOutputStream("G:\\xiangmu\\jichu\\wenjianjia\\c.txt"), "UTF-8"); //3.使用InputstreamReader对象中的方法read读取文件 int len = 0; while ((len = isr.read())!=-1){ //4.使用outputstreamwriter对象中的方法vrite,把读取的数据写入到文件中 ois.write(len); } //5 .释放资源 ois.close(); isr.close(); } }
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 分享4款.NET开源、免费、实用的商城系统
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
· 上周热点回顾(2.24-3.2)