Descobrir Charset de uma String

6 respostas
N

Teria como saber qual o Chaset, ou melhor, o encoding utilizado numa String?

ex: eu passo uma String “áéíó” e o método me retorna se é UTF-8 ou ISO-8859-1?

alguém já tentou fazer algo assim?

6 Respostas

T

http://jchardet.sourceforge.net/

N

veio … te amo …

vou testa e posto o resultado … vlw"

N

show .. brigadão bixo!

até fiz um metodozinho pra retornar os provaveis charsets ... :D

public static String[] getProbableCharsets(InputStream in) throws IOException {
		
		int lang = (in.available()<nsPSMDetector.ALL) ? in.available()  : nsPSMDetector.ALL; 
		nsDetector det = new nsDetector(lang);

		det.Init(new nsICharsetDetectionObserver() {
			public void Notify(String charset) {
				HtmlCharsetDetector.found = true;
			}
		});

		byte[] buf = IOUtils.toByteArray(in);
		int len  = buf.length;

		boolean isAscii = det.isAscii(buf, len);
		
		if(isAscii)
			return new String[] { "windows-1252" };
		
		String[] charsets = det.getProbableCharsets();
		det.DataEnd();

		return charsets;
	}
_

Valeu ai galera, também estava precisando disso ai xD

o/

F

Salve pessoal, a solução parece ser boa, mas precisa de bibliotecas externas e onde eu trabalho ha uma politica rigorosa referente ao uso de outras libs.
Alguem encontrou algum metodo similar para descobrir o encoding de uma string ?

J

Boa tarde Pessoal,
Eu precisava saber o Charset de uma String qualquer, então resolvi postar aqui a minha solução.

Segue o link CharsetDetector.
http://tika.apache.org/0.8/api/org/apache/tika/parser/txt/CharsetDetector.html
Dependência para quem esta utilizando Maven.

<dependency>
	<groupId>com.ibm.icu</groupId>
	<artifactId>icu4j</artifactId>
	<version>4.8</version>
</dependency>

Segue código

CharsetDetector charsetDetector = new CharsetDetector();
charsetDetector.setText(minhaString.getBytes()); // Aqui você seta sua String
CharsetMatch detect = charsetDetector.detect();

O método charsetDetector.detect() retorna um CharsetMatch.
Segue o link CharsetMatch
http://tika.apache.org/0.8/api/org/apache/tika/parser/txt/CharsetMatch.html
Para saber o encoding da sua String é só pegar o Name.

detect.getName(); // Exemplo de retorno: UTF-8, ISO-8859-1
Criado 18 de agosto de 2009
Ultima resposta 17 de mar. de 2015
Respostas 6
Participantes 5