上传txt文件判断编码格式,并转UTF-8
前言
提示:这里可以添加本文要记录的大概内容:
例如:随着人工智能的不断发展,机器学习这门技术也越来越重要,很多人都开启了学习机器学习,本文就介绍了机器学习的基础内容。
提示:以下是本篇文章正文内容,下面案例可供参考
一、使用步骤
代码如下(示例):
/*** @Author wdp* @Description //TODO * @Date 16:24 2021/3/18* @Param [file, inputFileUrl:源文件路径, outputFileUrl:新文件路径]* @return void**/public static void saveAsUTF8(File file,String inputFileUrl, String outputFileUrl) throws IOException {String inputFileEncode = getFilecharset(file);System.out.println("inputFileEncode===" + inputFileEncode);BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(new FileInputStream(inputFileUrl), inputFileEncode));BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(outputFileUrl), "UTF-8"));String line;while ((line = bufferedReader.readLine()) != null) {bufferedWriter.write(line + "\r\n");}bufferedWriter.close();bufferedReader.close();}//判断编码格式方法private static String getFilecharset(File sourceFile) {String charset = "GBK";byte[] first3Bytes = new byte[3];try {boolean checked = false;BufferedInputStream bis = new BufferedInputStream(new FileInputStream(sourceFile));bis.mark(0);int read = bis.read(first3Bytes, 0, 3);if (read == -1) {return charset; //文件编码为 ANSI} else if (first3Bytes[0] == (byte) 0xFF&& first3Bytes[1] == (byte) 0xFE) {charset = "UTF-16LE"; //文件编码为 Unicodechecked = true;} else if (first3Bytes[0] == (byte) 0xFE&& first3Bytes[1] == (byte) 0xFF) {charset = "UTF-16BE"; //文件编码为 Unicode big endianchecked = true;} else if (first3Bytes[0] == (byte) 0xEF&& first3Bytes[1] == (byte) 0xBB&& first3Bytes[2] == (byte) 0xBF) {charset = "UTF-8"; //文件编码为 UTF-8checked = true;}bis.reset();if (!checked) {int loc = 0;while ((read = bis.read()) != -1) {loc++;if (read >= 0xF0)break;if (0x80 <= read && read <= 0xBF) // 单独出现BF以下的,也算是GBKbreak;if (0xC0 <= read && read <= 0xDF) {read = bis.read();if (0x80 <= read && read <= 0xBF) // 双字节 (0xC0 - 0xDF)// (0x80// - 0xBF),也可能在GB编码内continue;elsebreak;} else if (0xE0 <= read && read <= 0xEF) {// 也有可能出错,但是几率较小read = bis.read();if (0x80 <= read && read <= 0xBF) {read = bis.read();if (0x80 <= read && read <= 0xBF) {charset = "UTF-8";break;} elsebreak;} elsebreak;}}}bis.close();} catch (Exception e) {e.printStackTrace();}return charset;}
2.备注
别忘了删除源文件
本文来自互联网用户投稿,文章观点仅代表作者本人,不代表本站立场,不承担相关法律责任。如若转载,请注明出处。 如若内容造成侵权/违法违规/事实不符,请点击【内容举报】进行投诉反馈!
