Java:How can i get the encoding from inputStream?

后端 未结 2 1970
执笔经年
执笔经年 2020-12-31 10:41

I want get the encoding from a stream.

1st method - to use the InputStreamReader.

But it always return OS encode.

I         


        
2条回答
  •  陌清茗
    陌清茗 (楼主)
    2020-12-31 10:58

        public String getDecoder(InputStream inputStream) {
    
        String encoding = null;
    
        try {
            byte[] buf = new byte[4096];
            UniversalDetector detector = new UniversalDetector(null);
            int nread;
    
            while ((nread = inputStream.read(buf)) > 0 && !detector.isDone()) {
                detector.handleData(buf, 0, nread);
            }
    
            detector.dataEnd();
            encoding = detector.getDetectedCharset();
            detector.reset();
    
            inputStream.close();
    
        } catch (Exception e) {
        }
    
        return encoding;
    }
    

提交回复
热议问题