1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67
|
import java.io.BufferedInputStream;
import java.io.ByteArrayInputStream;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import org.apache.log4j.Logger;
import org.mozilla.intl.chardet.nsDetector;
import org.mozilla.intl.chardet.nsPSMDetector;
public class CharsetInputHelper {
Logger logger = Logger.getLogger(CharsetInputHelper.class);
private nsDetector det = null;
private CharsetInputObserver obsvr = null;
public CharsetInputHelper ( ){
int lang = nsPSMDetector.ALL; //or nsPSMDetector.JAPANESE and so. See Jchardet API for more information
det = new nsDetector(lang);
obsvr = new CharsetInputObserver();
}
public String whichEncodingIs ( byte[] theData ){
boolean isAscii = true ;
det.Init( obsvr );
try {
// Check if the stream is only ascii.
if (isAscii)
isAscii = det.isAscii(theData,theData.length);
// DoIt if non-ascii and not done yet.
// Here I've removed the && !done
//because I wanted to see all charsets encodings
//that Jchardet detects in a file
if (!isAscii)
det.DoIt(theData,theData.length, false);
} catch (Exception e) {
// TODO Auto-generated catch block
System.err.println("[whichEncodingIs] Error : "+e.getMessage());
e.printStackTrace();
obsvr.setCharsetToUse("CP-500");
} finally {
det.DataEnd();
}
if (isAscii){
obsvr.setCharsetToUse("ASCII");
}
return obsvr.getCharsetToUse();
}
} |