【发布时间】:2016-02-18 03:13:49
【问题描述】:
有人可以帮我弄清楚我在这里做错了什么吗?这个方法除了在调用 new InputStreamReader(stream, getSet(stream); 时产生空行之外什么都不做
谢谢大家!
private static final byte[] UTF8_BOM = new byte[] {(byte) 0xEF, (byte) 0xBB, (byte) 0xBF};
private static final byte[] UTF16LE_BOM = new byte[] {(byte) 0xFF, (byte) 0xFE};
private static final byte[] UTF16BE_BOM = new byte[] {(byte) 0xFE, (byte) 0xFF};
public static Charset getSet(final InputStream stream) throws IOException {
final byte[] UTF8_Buffer = new byte[3];
final byte[] UTF16LE_Buffer = new byte[2];
final byte[] UTF16BE_Buffer = new byte[2];
int byteValue;
InputStream bufferedStream = new BufferedInputStream(stream);
bufferedStream.mark(3);
byteValue = stream.read();
UTF16LE_Buffer[0] = (byte) byteValue;
UTF16BE_Buffer[0] = (byte) byteValue;
UTF8_Buffer[0] = (byte) byteValue;
byteValue = bufferedStream.read();
UTF16LE_Buffer[1] = (byte) byteValue;
UTF16BE_Buffer[1] = (byte) byteValue;
UTF8_Buffer[1] = (byte) byteValue;
if (Arrays.equals(UTF16LE_Buffer, UTF16LE_BOM)) {
return StandardCharsets.UTF_16LE;
} else if (Arrays.equals(UTF16BE_Buffer, UTF16LE_BOM)) {
return StandardCharsets.UTF_16BE;
} else {
byteValue = bufferedStream.read();
UTF8_Buffer[2] = (byte) byteValue;
if (Arrays.equals(UTF8_Buffer, UTF8_BOM)) {
return StandardCharsets.UTF_8;
}
}
bufferedStream.reset();
return StandardCharsets.UTF_8;
}
【问题讨论】:
-
你试过在调试模式下运行代码吗?
-
是的,我似乎在第一次
bufferedStream.read()通话中得到-1。感谢阿尔伯特!为了格式化我的代码,我无法将所有内容都放入代码块中 -
我刚刚在调试中再次运行它,我错了,我得到的值不是-1。
-
你能不能把值写在这里以便其他人也能看到
-
没错,第一次调用返回:224 第二次返回164,第三次调用返回174
标签: java java-io bufferedinputstream