public static Optional < Charset > charset ( File file ) { if ( ! file . exists ( ) ) { logger . error ( "The file [ {} ] is not exist." , file . getAbsolutePath ( ) ) ; return Optional . absent ( ) ; } FileInputStream fileInputStream = null ; BufferedInputStream bin = null ; try { fileInputStream = new FileInputStream ( file ) ; bin = new BufferedInputStream ( fileInputStream ) ; int p = ( bin . read ( ) << 8 ) + bin . read ( ) ; Optional < Charset > charset ; //其中的 0xefbb、0xfffe、0xfeff、0x5c75这些都是这个文件的前面两个字节的16进制数 switch ( p ) { case 0xefbb : charset = Optional . of ( Charsets . UTF_8 ) ; break ; case 0xfffe : charset = Optional . of ( Charset . forName ( "Unicode" ) ) ; break ; case 0xfeff : charset = Optional . of ( Charsets . UTF_16BE ) ; break ; case 0x5c75 : charset = Optional . of ( Charsets . US_ASCII ) ; break ; default : charset = Optional . of ( Charset . forName ( "GBK" ) ) ; } return charset ; } catch ( FileNotFoundException e ) { logger . error ( "The file [ {} ] is not exist." , file . getAbsolutePath ( ) , e ) ; } catch ( IOException e ) { logger . error ( "Read file has error, {}." , file . getAbsolutePath ( ) , e ) ; } finally { IOUtils . closeQuietly ( fileInputStream ) ; IOUtils . closeQuietly ( bin ) ; } return Optional . absent ( ) ; }
Get coding format file .