gpt4 book ai didi

Java笔记-解决读取文件时中文乱码问题(InputStreamReader设置编码)

转载 作者:知者 更新时间:2024-03-13 02:53:07 28 4
gpt4 key购买 nike

Java一般读取文件时使用如下代码:

InputStream inputStream = this.getClass().getClassLoader().getResourceAsStream("xxx");

BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream);
while(reader.ready()){

    String line = reader.readLine();
    System.out.println(line);
}
reader.close();
inputStream.close();

有时,这个文件是utf-8的,Java默认是能读的,有的是GBK的,可以用InputStreamReader设置编码

InputStream inputStream = this.getClass().getClassLoader().getResourceAsStream("xxx");

BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, "gbk");
while(reader.ready()){

    String line = reader.readLine();
    System.out.println(line);
}
reader.close();
inputStream.close();

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com