獲取讀取到的字節流中的文件編碼防止亂碼

1.pom.xml加入:

<!-- https://mvnrepository.com/artifact/com.googlecode.juniversalchardet/juniversalchardet -->
<dependency>
  <groupId>com.googlecode.juniversalchardet</groupId>
  <artifactId>juniversalchardet</artifactId>
  <version>1.0.3</version>
</dependency>

 

2.  工具類

  class GetByteEncode {
    String getEncoding(byte[] bytes) {
      String deafultCode = "UTF-8";
      UniversalDetector detector = new UniversalDetector(null);
      detector.handleData(bytes, 0, bytes.length);
      detector.dataEnd();
      String encoding = detector.getDetectedCharset();
      detector.reset();
      if (encoding == null) {
        encoding = deafultCode;
      }
      return encoding;
    }
  }

3.使用:

 String filenameIso = new String(data.getFileName().getBytes("UTF-8"), "iso-8859-1");
        /* 設置文件名 */
        response.addHeader("Content-Disposition", "fileName=\"" + filenameIso + "\"");
        os = response.getOutputStream();
        byte[] b = fileInfo.getData().getFileByte();
        String encoding = new GetByteEncode().getEncoding(b); //編碼判斷 --動態
        response.setHeader("Content-type", "text/html;charset=" + encoding);
        String a = new String(fileInfo.getData().getFileByte(), encoding);
        os.write(a.getBytes(encoding));

 

 

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章