Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save shirmanov/555233 to your computer and use it in GitHub Desktop.
Save shirmanov/555233 to your computer and use it in GitHub Desktop.
// Blog post:
// http://www.shirmanov.com/2010/08/byteordermark-handling-byte-order-mark.html
package com.blueoceansystems.samples;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import com.google.common.base.Charsets;
// Usage:
// InputStream in;
// Reader reader;
// try {
// reader = ByteOrderMark.handleFrom( in ).getInputStreamReader();
// } catch( IOException ex ) {
// // Empty
// }
public final class ByteOrderMark {
private InputStream _inputStream;
private ByteOrderMark( InputStream inputStream ) {
this._inputStream = inputStream;
}
public static ByteOrderMark handleFrom( InputStream inputStream ) {
return new ByteOrderMark( inputStream );
}
public Reader getInputStreamReader() throws IOException {
_inputStream.mark( 3 );
int byte1 = _inputStream.read();
int byte2 = _inputStream.read();
if( byte1 == 0xFF && byte2 == 0xFE ) {
return new InputStreamReader( _inputStream, Charsets.UTF_16LE );
} else if( byte1 == 0xFF && byte2 == 0xFF ) {
return new InputStreamReader( _inputStream, Charsets.UTF_16BE );
} else {
int byte3 = _inputStream.read();
if (byte1 == 0xEF && byte2 == 0xBB && byte3 == 0xBF) {
return new InputStreamReader( _inputStream, Charsets.UTF_8 );
} else {
_inputStream.reset();
return new InputStreamReader( _inputStream );
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment