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();
    }
}

 

posted @ 2022-07-13 14:08  zj勇敢飞,xx永相随  阅读(41)  评论(0编辑  收藏  举报