Java 自动转换为Unicode文件

来源:互联网 发布:大淘宝客联盟 编辑:程序博客网 时间:2024/05/21 00:46

说明:改博客主要是将windows 下(ASNI,Unicode,UTF-8,Unicode big endian)文件自动转换为Unicode 文件。


 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";//"文件编码 UTF-8"            } else if ((bf[0] == -1 && bf[1] == -2)) {                charSet = "x-UTF-16LE-BOM";//"文件编码 Unicode"            } else if ((bf[0] == -2 && bf[1] == -1)) {                charSet = "Unicode";//"文件编码 Unicode big endian"            } else {                charSet = "GBK";//"文件编码 ANSI"            }        } catch (Exception e) {            e.printStackTrace();        }        return charSet;    }    public static void main(String[] args) throws IOException {        try {            String fileName="D:\\write.srt";            InputStreamReader reader = new InputStreamReader(new FileInputStream(fileName),getFileEncode(fileName));            //x-UTF-16LE-BOM            OutputStreamWriter writer = new OutputStreamWriter(new FileOutputStream(new File("D:\\read.srt")), "x-UTF-16LE-BOM");            int temp = 0;            while ((temp = reader.read()) != -1) {                writer.write(temp);            }            reader.close();            writer.flush();            writer.close();        } catch (FileNotFoundException e) {            e.printStackTrace();        }    }