Created
April 20, 2013 00:32
-
-
Save lnds/5424160 to your computer and use it in GitHub Desktop.
Clase que permite abrir archivos detectando su encoding en forma automática, muy útil para trabajar con archivos codificados en WIndows Ansi, UTF8, Unicode, etc. Un problema que se está haciendo demasiado frecuente. Usa la biblioteca universalchardet de Mozilla
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| import org.mozilla.universalchardet.UniversalDetector; | |
| import java.io.*; | |
| import java.nio.charset.Charset; | |
| public class DetectEncoding { | |
| private static final int BUF_SIZE = 4096; | |
| // open a BufferedReader detect encoding | |
| public static BufferedReader openStream(String filename) throws IOException { | |
| String charsetName = detectEncoding(filename); | |
| Charset charset = charsetName == null ? Charset.defaultCharset() : Charset.forName(charsetName); | |
| return new BufferedReader(new InputStreamReader(new FileInputStream(filename), charset)); | |
| } | |
| // detect encoding of filename | |
| public static String detectEncoding(String filename) throws IOException{ | |
| FileInputStream fis = new FileInputStream(filename); | |
| UniversalDetector detector = new UniversalDetector(null); | |
| int nread; | |
| byte[] buf = new byte[BUF_SIZE]; | |
| while ((nread = fis.read(buf)) > 0 && !detector.isDone()) { | |
| detector.handleData(buf, 0, nread); | |
| } | |
| detector.dataEnd(); | |
| String charset = detector.getDetectedCharset(); | |
| detector.reset(); | |
| return charset; | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment