Created
August 28, 2010 15:13
-
-
Save shirmanov/555233 to your computer and use it in GitHub Desktop.
This file contains 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
// 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