判断文本文件的编码类型

时间 2021/2/23 17:45:30 加载中...

判断文本文件的编码类型

项目:Spring Boot 项目

在 pom.xml 文件中引入依赖:

  1. <!-- https://mvnrepository.com/artifact/com.googlecode.juniversalchardet/juniversalchardet -->
  2. <dependency>
  3. <groupId>com.googlecode.juniversalchardet</groupId>
  4. <artifactId>juniversalchardet</artifactId>
  5. <version>1.0.3</version>
  6. </dependency>
  1. public static String detector(String fileName) {
  2. String encode = null;
  3. BufferedInputStream bis = null;
  4. try {
  5. bis = new BufferedInputStream(new FileInputStream(fileName));
  6. int readSize;
  7. byte[] buffer = new byte[8 * 4096];
  8. UniversalDetector detector = new UniversalDetector(null);
  9. while ((readSize = bis.read(buffer)) > 0 && !detector.isDone()) {
  10. detector.handleData(buffer, 0, readSize);
  11. }
  12. detector.dataEnd();
  13. encode = detector.getDetectedCharset();
  14. detector.reset();
  15. } catch (Exception e) {
  16. } finally {
  17. if (bis != null) {
  18. try {
  19. bis.close();
  20. } catch (IOException e) {
  21. e.printStackTrace();
  22. }
  23. }
  24. }
  25. //return encode;
  26. return encode.equalsIgnoreCase("UTF-8") ? "UTF-8" : "GBK";
  27. }
扫码分享
版权说明
作者:SQBER
文章来源:http://www.sqber.com/articles/detect-file-code.html
本文版权归作者所有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利。