io流中的txt文件编码更改

public static void main(String[] args){
File file = new File(filePath);
String str = readTxt(file);
FileOutputStream writerStream = new FileOutputStream(file); 
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(writerStream, "UTF-8")); 
writer.write(str);// 将read到的str以UTF-8的编码重新写入
writer.close(); 
}

// 读取txt文件中的内容,返回字符串
public static String readTxt(File file) {
StringBuilder result = new StringBuilder();
try {
InputStreamReader isr = new InputStreamReader(new FileInputStream(file), "GBK");
BufferedReader read = new BufferedReader(isr);
String s = null;
while ((s = read.readLine()) != null) {// 使用readLine方法,一次读一行
result.append(System.lineSeparator() + s);
}
read.close();
} catch (Exception e) {
e.printStackTrace();
}
return result.toString();
}

思路:因为txt文件的默认编码为GBK,所以先以GBK读取txt文件中的内容,存到字符串中,再将字符串以UTF-8的方式重新写入txt文件。

PS:正常应该是可以直接更改txt文件中内容的编码,时间有限,先做记录。

 

posted @ 2018-05-11 15:34  下一站_jn  阅读(151)  评论(0编辑  收藏  举报