| ページ一覧 | ブログ | twitter |  書式 | 書式(表) |

MyMemoWiki

Java 文字コード判定

提供: MyMemoWiki
ナビゲーションに移動 検索に移動

Java 文字コード判定

Java | テンプレート:Cateogry 文字化け

public static String detectEncoding(String text) {
    String encoding = null;

    try {
        UniversalDetector detector = new UniversalDetector(null);

        InputStream is = new StringInputStream(text);
        
        byte[] buf = new byte[1024];
        int nread;
        while ((nread = is.read(buf)) > 0 && !detector.isDone()) {
            detector.handleData(buf, 0, nread);
        }
        detector.dataEnd();
        encoding = detector.getDetectedCharset();
        
        detector.reset();
        
    } catch(Exception e) {
        e.printStackTrace();
    }
    
    return encoding;
}