public static void transcodeFile(InputStream inputStream, OutputStream outputStream, byte[] bf) throws IOException {
try {
src = new InputStreamReader(inputStream, getFileEncode(bf));
dst=new OutputStreamWriter(outputStream,"x-UTF-16LE-BOM");
int bufferLen;
while ((bufferLen = src.read()) != -1) {
dst.write(bufferLen);
}
} catch (Exception e) {
e.toString();
} finally {
src.close();
dst.close();
}
}
Java 可以自动识别文件编码:
public static String getFileEncode(String fileName) {
String charSet = "";
try {
FileInputStream fis = new FileInputStream(new File("D:\\write.srt"));
byte[] bf = new byte[3];
fis.read(bf);
fis.close();
if (bf[0] == -17 && bf[1] == -69 && bf[2] == -65) {
charSet = "UTF-8";
} else if ((bf[0] == -1 && bf[1] == -2)) {
charSet = "Unicode";
} else if ((bf[0] == -2 && bf[1] == -1)) {
charSet = "Unicode big endian";
} else {
charSet = "ANSI";
}
} catch (Exception e) {
e.printStackTrace();
}
return charSet;
}