private static String ReadUTF8WithBOMToString(String filePath) throws IOException
{
    String defaultEncoding = "UTF-8";
    InputStream inputStream = new FileInputStream(filePath);
    StringBuffer fileData = new StringBuffer();
    
    try {
        BOMInputStream bOMInputStream = new BOMInputStream(inputStream);
        ByteOrderMark bom = bOMInputStream.getBOM();
        String charsetName = bom == null ? defaultEncoding : bom.getCharsetName();
        InputStreamReader isr = new InputStreamReader(new BufferedInputStream(bOMInputStream), charsetName);
        BufferedReader reader = new BufferedReader(isr);
        char[] buf = new char[1024];
        int numRead = 0;
        while((numRead=reader.read(buf)) != -1)
        {
            String readData = String.valueOf(buf, 0, numRead);
            fileData.append(readData);
        }
        reader.close();
        return fileData.toString();
    } finally {
        inputStream.close();
    }
}

用到了一个jar包 Apache Commons IO, java 读取 utf-8 bom 出现乱码 https://img2020.cnblogs.com/blog/65667/202008/65667-20200812160049507-807397496.jpg,将图片链接下载后改名为 commons-io-2.7.jar

相关文章:

  • 2022-02-09
  • 2022-12-23
  • 2022-02-27
  • 2022-03-10
  • 2021-10-27
  • 2022-12-23
  • 2022-12-23
  • 2021-06-25
猜你喜欢
  • 2022-12-23
  • 2021-05-24
  • 2022-12-23
  • 2022-12-23
  • 2021-07-15
  • 2021-12-01
相关资源
相似解决方案