背景:
使用windows自带的记事本,另存为一个文本文件,可以看到当前文本编码,有这么几种格式,ANSI,Unicode,UTF-8,如果某个文档使用了其中一种编码方式,那么就必须要使用该编码方式打开,如果不适配编码方式的,后果
就是得到一堆的乱码,比较烦,查找网上相关资料,终于找到一种通用的解决方案,就是先获取源文件的编码格式,然后使用该编码方式来读取这个文件,实现代码如下:
代码:
‘
/**
* 抽取txt中所有文字
*
* @param path
* @return
*/
public static String readTxt(String path) {
StringBuilder content = new StringBuilder();
try {
File file = new File(path);
InputStream is = new FileInputStream(file);
InputStreamReader isr = new InputStreamReader(is, getFilecharset(file));
BufferedReader br = new BufferedReader(isr);
String str;
while (null != (str = br.readLine())) {
content.append(str);
}
br.close