public static String resolveCode(String path) throws Exception {
/* String code = resolveCode(path);
File file = new File(path);
InputStream is = new FileInputStream(file);
InputStreamReader isr = new InputStreamReader(is, code);
BufferedReader br = new BufferedReader(isr);*/
InputStream inputStream = new FileInputStream(path);
byte[] head = new byte[3];
inputStream.read(head);
String code = "gb2312"; //或GBK
if (head[0] == -1 && head[1] == -2 )
code = "UTF-16";
else if (head[0] == -2 && head[1] == -1 )
code = "Unicode";
else if(head[0]==-17 && head[1]==-69 && head[2] ==-65)
code = "UTF-8";
inputStream.close();
System.out.println(code);
return code;
}
1.上面代码获取txt文档的编码格式
2.读取txt内容时候为防止中文乱码,设置读取时候编码格式和txt文本编码格式一致
InputStreamReader isr = new InputStreamReader(new FileInputStream(new File(path)), /*resolveCode(path)*/resolveCode(path));设置读取txt时候的编码格式
3.写入txt文档编码格式
BufferedWriter writer = new BufferedWriter (new OutputStreamWriter (new FileOutputStream (path,false),"utf-8"));//resolveCode(path)//设置格式utf-8读取时候一般不会中文乱码