Loading

Java读取本地文件乱码的解决方案

首先需要说明读文件的两种最常见的方式:

第一种是:getResourceAsStream(fileName)
第二种是:

String filePath = ReadAndWriteHandler.class.getClassLoader().getResource(FILE_NAME).getFile();
filePath = java.net.URLDecoder.decode(filePath, ENCODING);
File file = new File(filePath);

不管是哪一种,一般都需要传入 new InputStreamReader(xxx) 中
此时,如果不给 new InputStreamReader(xxx) 加编码参数,会采用默认的本机默认的编码(如Win的GBK)读入。
如果,文件格式是utf-8,此时,就会出现乱码,因此,对于utf-8编码的文件,我们需要加上编码参数:

new InputStreamReader(xxx, "utf-8"); 
posted @ 2020-06-11 17:16  Doubest  阅读(1003)  评论(0编辑  收藏  举报