指定编码“gbk“,防止中文字符乱码

 实现过程如下:

/**
 * 演示使用 InputStreamReader 转换流解决中文乱码问题
 * 将字节流 FileInputStream 转成字符流 InputStreamReader,指定编码 gbk/UTF-8
 */
public class InputStreamReader_ {
    public static void main(String[] args) throws IOException {
        String filePath = "E:\\aa.txt";
        //1.把 FileInputStream 转成 InputStreamReader
        //2.指定编码 gbk
        InputStreamReader iSr = new InputStreamReader(new FileInputStream(filePath), "gbk");
        //3.把 InputStreamReader 传入 BufferedReader
        BufferedReader br = new BufferedReader(iSr);
        String s =null;
        while((s=br.readLine())!=null){
            System.out.print(s+"\n");
        }
        br.close();
    }
}

 

public class InputStreamReader_ {
    public static void main(String[] args) throws IOException {
        String filePath = "E:\\aa.txt";
        //1.把 FileInputStream 转成 InputStreamReader
        //2.指定编码 gbk
"gbk");
        //3.把 InputStreamReader 传入 BufferedReader
        InputStreamReader isr = new InputStreamReader(new BufferedInputStream(new FileInputStream(filePath)),"gbk");
        int s = 0;
        while ((s = isr.read())!= -1) {
            System.out.print((char)s);
        }
        isr.close();
    }
}
public class InputStreamReader_02 {
    public static void main(String[] args) throws IOException {
        String filePath = "E:\\aa.txt";
        //1.把 FileInputStream 转成 InputStreamReader
        //2.指定编码 gbk
//        InputStreamReader iSr = new InputStreamReader(new FileInputStream(filePath), "gbk");
//        //3.把 InputStreamReader 传入 BufferedReader
//        BufferedReader br = new BufferedReader(iSr);
        //将2,3整合到一起
        BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(filePath),"gbk"));
        String s =null;
        while((s=br.readLine())!=null){
            System.out.print(s+"\n");
        }
        br.close();
    }
}

 InputStreamReader的底层源码如下,可以传递参数charsetName,防止中文乱码

public InputStreamReader(InputStream in, String charsetName)
        throws UnsupportedEncodingException
    {
        super(in);
        if (charsetName == null)
            throw new NullPointerException("charsetName");
        sd = StreamDecoder.forInputStreamReader(in, this, charsetName);
    }

你可能感兴趣的:(韩顺平java习题,Java碧血指南,java,servlet,开发语言)