get File Stream Encoding - Android File Input Output

Android examples for File Input Output:File Charset

Description

get File Stream Encoding

Demo Code


//package com.java2s;
import java.io.BufferedInputStream;

import java.io.IOException;
import java.io.InputStream;

public class Main {

    public static String getStreamEncoding(InputStream is)
            throws IOException {
        BufferedInputStream bis = new BufferedInputStream(is);
        bis.mark(2);//from www  .j ava 2s .  c  om
        byte[] first3bytes = new byte[3];
        bis.read(first3bytes);
        bis.reset();
        String encoding = null;
        if (first3bytes[0] == (byte) 0xEF && first3bytes[1] == (byte) 0xBB
                && first3bytes[2] == (byte) 0xBF) {
            encoding = "utf-8";
        } else if (first3bytes[0] == (byte) 0xFF
                && first3bytes[1] == (byte) 0xFE) {
            encoding = "unicode";
        } else if (first3bytes[0] == (byte) 0xFE
                && first3bytes[1] == (byte) 0xFF) {
            encoding = "utf-16be";
        } else if (first3bytes[0] == (byte) 0xFF
                && first3bytes[1] == (byte) 0xFF) {
            encoding = "utf-16le";
        } else {
            encoding = "GBK";
        }
        return encoding;
    }
}

Related Tutorials