Java读中文乱码解决方案

解决从文本文件中读入数据后输出,发现中文乱码问题。
下面的这个两个例子很好的解决了这个问题!

package day1029;

import java.io.*;

public class TestPrintStreamAndWriter {
    public static void main(String[] args) {
        new TestPrintStreamAndWriter().TestPrintWriter();
    }

    private void TestPrintStream() {
        // 从读出的字节中直接转换为gbk 所以不会乱码
        BufferedInputStream bis = null;
        PrintStream ps = null;
        try {
            bis = new BufferedInputStream(new FileInputStream(new File("D:\\文档\\p.txt")));
            // 把输出流设置为控制台
            ps = new PrintStream(System.out);
            byte[] bytes = new byte[bis.available()];
            if (bis.read(bytes, 0, bytes.length) > 0) {
                ps.print(new String(bytes, "gbk"));
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (ps != null) {
                ps.close();
            }
            if (bis != null) {
                try {
                    bis.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    private void TestPrintWriter() {
        BufferedReader br = null;
        PrintWriter pw = null;
        try {
            // 文件的读取顺序是FileInputStream以字节的方式把文件读出来,
            // 然后通过转换流InputStreamReader把它以gbk的方式编码,
            // 编成gbk的字符,然后BufferedReader再读取转换后的字符,
            // 这样输出就不会乱码了
            br = new BufferedReader(new InputStreamReader(new FileInputStream("D:\\文档\\p.txt"), "gbk"));
            // 重定向
            pw = new PrintWriter(System.out);
            String s = null;
            while ((s = br.readLine()) != null) {
                pw.println(s);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (pw != null) {
                pw.close();
            }
            if (br != null) {
                try {
                    br.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}

TestPrintStream()方法是以字节流的方式读取数据,然后在输出的时候new String(bytes, "gbk")是这样的。意思就是,Stirng要把bytes里的字节以gbk的方式进行编码,然后再输出。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值