BufferedInputStream标记/重置问题

时间:2015-11-16 21:47:53

标签: java java-io bufferedinputstream

有人可以帮我弄清楚我在做错了吗?除了在调用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;
      }

2 个答案:

答案 0 :(得分:1)

这里的问题是您已经使用BufferedInputStream从输入流中读取了两个或三个字节。在mark()/reset()上调用BufferedInputStream可以让您从BufferedInputStream 重新读取这些字节,但它对基础流没有任何作用。

您应该更改此方法的调用方以传递BufferedInputStream而不是InputStream,并从方法中删除new BufferedInputStream,以便调用方和被调用方都是标记/重置相同的流。如果调用者未传递支持InputStream的{​​{1}},则调用其中任何一个都会引发异常。

答案 1 :(得分:-2)

我找到了解决问题的方法。

我改变了这个方法:

public static String readText(@Nonnull final InputStream stream) throws IOException {
     try (final Reader reader = new InputStreamReader(stream, getCharset(stream))) {....

对此:

public static String readText(@Nonnull final InputStream stream) throws   IOException {
    final BufferedInputStream bufferedStream = new BufferedInputStream(stream);
    try (final Reader reader = new InputStreamReader(bufferedStream, getCharset(bufferedStream))) {...

感谢所有帮助人员!