概述
利用io流读写文件时,默认的流编码都是UTF-8,d但是如果流的编码和文件的编码不一样,得到的内容是乱码.所幸的是字节流可以在转为String使用new String(byte[],charset)设置编码.字符流InputStreamReader,OutputStreamWriter这两个类的构造方法提供了设置流编码的方法.
下面举个简单的例子,其他情况可以举一反三.
读取的文件是GBK编码,写入的文件是UTF-8编码
@Test
public void test4(){
BufferedWriter bufferedWriter = null;
BufferedReader bufferedReader = null;
try {
bufferedReader = new BufferedReader(new InputStreamReader(new FileInputStream("G://20180920.txt"),"GBK"));
//开始写入内容
bufferedWriter = new BufferedWriter(new OutputStreamWriter(new FileOutputStream("G://bz20180920.txt"),"UTF-8"));
String line,poundage;
String separator = "|";
StringBuilder sb;
while ((line = bufferedReader.readLine()) != null) {
String[] contents = line.split("\\|");
poundage = contents[7];
while (poundage.length() != 12){
poundage = "0" + poundage;
}
sb = new StringBuilder();
sb.append(contents[0]).append(separator)
.append(contents[8]).append(separator)
.append(contents[2]).append(separator)
.append(getStatus(contents[10])).append(separator)
.append(getStatus(contents[10])).append(separator)
.append(contents[11]).append(separator)
.append("DIS").append(separator)
.append("OT001").append(separator)
.append(separator)
.append("F01").append(separator)
.append(poundage).append(separator)
.append(separator)
.append(separator)
.append(separator)
.append(separator)
.append(separator)
.append("\r\n");
bufferedWriter.write(sb.toString());
bufferedWriter.flush();
}
}catch (Exception e) {
log.error("处理的文件发生异常:{}", e);
} finally {
if (bufferedWriter != null) {
try {
bufferedWriter.close();
} catch (IOException e) {
log.error("关闭输出流异常:{}", e);
}
}
if (bufferedReader != null) {
try {
bufferedReader.close();
} catch (IOException e) {
log.error("关闭读取流异常:{}", e);
}
}
}
}
private String getStatus(String s) {
if ("SUCCESS".equals(s)){
return "000";
}
return "020";
}