JAVA_IO_FileReader读取txt文件乱码问题

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_40646143/article/details/84142746

今天使用FileReader读取txt文件,java后台一直乱码,搞了好久才解决,在此记录一下.

Java中的字符流处理的最基本的单元是Unicode码元(大小2字节),分为Reader-读取,Writer-写入,它通常处理文本数据如.txt,.html等

这是txt文件

                                      

java读取

public static void main(String [] args) throws IOException {
        Reader reader=null;
        StringBuffer sb=new StringBuffer();
        try {
            reader = new FileReader(new File("C:/Users/xiao/Desktop/text.txt"));
            char[] chars = new char[1024];
            int len;
            while ((len=reader.read(chars))!=-1){
                String s = new String(chars, 0, len);
                sb.append(s);
            }
            System.out.println(sb.toString());

        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            if (reader!=null)
            reader.close();
        }

    }

通过debug断点可以看出来读取txt文件的时候,直接乱码了,如下

后来google了好,终于找到了问题所在

                                       

我的是这样的所以会乱码

在调试一遍就不会乱码了,如下

猜你喜欢

转载自blog.csdn.net/qq_40646143/article/details/84142746