当前位置: 首页>>代码示例>>Java>>正文


Java ByteArrayInputStream.reset方法代码示例

本文整理汇总了Java中java.io.ByteArrayInputStream.reset方法的典型用法代码示例。如果您正苦于以下问题:Java ByteArrayInputStream.reset方法的具体用法?Java ByteArrayInputStream.reset怎么用?Java ByteArrayInputStream.reset使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在java.io.ByteArrayInputStream的用法示例。


在下文中一共展示了ByteArrayInputStream.reset方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。

示例1: readMarkAndReset

import java.io.ByteArrayInputStream; //导入方法依赖的package包/类
public void readMarkAndReset(byte[] bytes,int mark) {
    StringBuffer sb = new StringBuffer();
    ByteArrayInputStream bais = new ByteArrayInputStream(bytes);
    bais.mark(mark);

    bais.skip(mark + 1);
    int tmp;
    while ((tmp = bais.read()) != -1) {
        sb.append(Integer.toHexString(tmp));
    }

    System.out.println("越过标记后的字符串");
    System.out.println(sb.toString());

    bais.reset();
    sb.setLength(0);

    int m;
    while ((m = bais.read()) != -1) {
        sb.append(Integer.toHexString(m));
    }

    System.out.println("重置之后的字符串");
    System.out.println(sb.toString());
}
 
开发者ID:byhieg,项目名称:JavaTutorial,代码行数:26,代码来源:ByteArrayInputStreamExample.java

示例2: detectEncodingStr

import java.io.ByteArrayInputStream; //导入方法依赖的package包/类
public String detectEncodingStr(ByteArrayInputStream inputStream,int len){
    String strEnc ="UTF-8";
    try{

        byte buffers[] = new byte[len];

        inputStream.read(buffers,0,len);
        inputStream.reset();

        int enc = detectEncoding(buffers);
        if (enc!=-1){
            String encStr =  Encoding.htmlname[enc];
            if (!encStr.equals("ASCII")){
                strEnc = encStr;
            }
        }
    }catch (Exception e){

    }
    return strEnc;
}
 
开发者ID:yale8848,项目名称:CacheWebView,代码行数:22,代码来源:BytesEncodingDetect.java

示例3: getArrayOfStringValues

import java.io.ByteArrayInputStream; //导入方法依赖的package包/类
/**
 * Returns array of String values.
 */
public String[] getArrayOfStringValues() {

    byte[] bufArray = (byte[])myValue;
    if (bufArray != null) {
        ByteArrayInputStream bufStream =
            new ByteArrayInputStream(bufArray);
        int available = bufStream.available();

        // total number of values is at the end of the stream
        bufStream.mark(available);
        bufStream.skip(available-1);
        int length = bufStream.read();
        bufStream.reset();

        String[] valueArray = new String[length];
        for (int i = 0; i < length; i++) {
            // read length
            int valLength = bufStream.read();
            byte[] bufBytes = new byte[valLength];
            bufStream.read(bufBytes, 0, valLength);
            try {
                valueArray[i] = new String(bufBytes, "UTF-8");
            } catch (java.io.UnsupportedEncodingException uee) {
            }
        }
        return valueArray;
    }
    return null;
}
 
开发者ID:lambdalab-mirror,项目名称:jdk8u-jdk,代码行数:33,代码来源:AttributeClass.java

示例4: testParseCentralDirectoryEntry

import java.io.ByteArrayInputStream; //导入方法依赖的package包/类
@Test
public void testParseCentralDirectoryEntry() throws Exception {
  ByteArrayInputStream in = new ByteArrayInputStream(unitTestZipArchive);
  in.mark(unitTestZipArchive.length);
  int eocdOffset = MinimalZipParser.locateStartOfEocd(unitTestZipArchive);
  Assert.assertEquals(eocdOffset, in.skip(eocdOffset));
  MinimalCentralDirectoryMetadata metadata = MinimalZipParser.parseEocd(in);
  in.reset();
  Assert.assertEquals(
      metadata.getOffsetOfCentralDirectory(), in.skip(metadata.getOffsetOfCentralDirectory()));

  // Read each entry and verify all fields *except* the value returned by
  // MinimalZipEntry.getFileOffsetOfCompressedData(), as that has yet to be computed.
  for (UnitTestZipEntry expectedEntry : UnitTestZipArchive.allEntriesInFileOrder) {
    MinimalZipEntry parsed = MinimalZipParser.parseCentralDirectoryEntry(in);
    Assert.assertEquals(expectedEntry.path, parsed.getFileName());

    // Verify that the local signature header is at the calculated position
    byte[] expectedSignatureBlock = new byte[] {0x50, 0x4b, 0x03, 0x04};
    for (int index = 0; index < 4; index++) {
      byte actualByte = unitTestZipArchive[((int) parsed.getFileOffsetOfLocalEntry()) + index];
      Assert.assertEquals(expectedSignatureBlock[index], actualByte);
    }

    if (expectedEntry.level > 0) {
      Assert.assertEquals(8 /* deflate */, parsed.getCompressionMethod());
    } else {
      Assert.assertEquals(0 /* store */, parsed.getCompressionMethod());
    }
    byte[] uncompressedContent = expectedEntry.getUncompressedBinaryContent();
    Assert.assertEquals(uncompressedContent.length, parsed.getUncompressedSize());
    CRC32 crc32 = new CRC32();
    crc32.update(uncompressedContent);
    Assert.assertEquals(crc32.getValue(), parsed.getCrc32OfUncompressedData());
    byte[] compressedContent = expectedEntry.getCompressedBinaryContent();
    Assert.assertEquals(compressedContent.length, parsed.getCompressedSize());
  }
}
 
开发者ID:lizhangqu,项目名称:CorePatch,代码行数:39,代码来源:MinimalZipParserTest.java

示例5: testParseLocalEntryAndGetCompressedDataOffset

import java.io.ByteArrayInputStream; //导入方法依赖的package包/类
@Test
public void testParseLocalEntryAndGetCompressedDataOffset() throws Exception {
  ByteArrayInputStream in = new ByteArrayInputStream(unitTestZipArchive);
  in.mark(unitTestZipArchive.length);
  int eocdOffset = MinimalZipParser.locateStartOfEocd(unitTestZipArchive);
  Assert.assertEquals(eocdOffset, in.skip(eocdOffset));
  MinimalCentralDirectoryMetadata metadata = MinimalZipParser.parseEocd(in);
  in.reset();
  Assert.assertEquals(
      metadata.getOffsetOfCentralDirectory(), in.skip(metadata.getOffsetOfCentralDirectory()));

  // Read each entry and verify all fields *except* the value returned by
  // MinimalZipEntry.getFileOffsetOfCompressedData(), as that has yet to be computed.
  List<MinimalZipEntry> parsedEntries = new ArrayList<MinimalZipEntry>();
  for (int x = 0; x < UnitTestZipArchive.allEntriesInFileOrder.size(); x++) {
    parsedEntries.add(MinimalZipParser.parseCentralDirectoryEntry(in));
  }

  for (int x = 0; x < UnitTestZipArchive.allEntriesInFileOrder.size(); x++) {
    UnitTestZipEntry expectedEntry = UnitTestZipArchive.allEntriesInFileOrder.get(x);
    MinimalZipEntry parsedEntry = parsedEntries.get(x);
    in.reset();
    Assert.assertEquals(
        parsedEntry.getFileOffsetOfLocalEntry(),
        in.skip(parsedEntry.getFileOffsetOfLocalEntry()));
    long relativeDataOffset = MinimalZipParser.parseLocalEntryAndGetCompressedDataOffset(in);
    Assert.assertTrue(relativeDataOffset > 0);
    checkExpectedBytes(
        expectedEntry.getCompressedBinaryContent(),
        (int) (parsedEntry.getFileOffsetOfLocalEntry() + relativeDataOffset));
  }
}
 
开发者ID:lizhangqu,项目名称:CorePatch,代码行数:33,代码来源:MinimalZipParserTest.java

示例6: getArrayOfIntValues

import java.io.ByteArrayInputStream; //导入方法依赖的package包/类
/**
 * Returns array of int values.
 */
public int[] getArrayOfIntValues() {

    byte[] bufArray = (byte[])myValue;
    if (bufArray != null) {

        //ArrayList valList = new ArrayList();
        ByteArrayInputStream bufStream =
            new ByteArrayInputStream(bufArray);
        int available = bufStream.available();

        // total number of values is at the end of the stream
        bufStream.mark(available);
        bufStream.skip(available-1);
        int length = bufStream.read();
        bufStream.reset();

        int[] valueArray = new int[length];
        for (int i = 0; i < length; i++) {
            // read length
            int valLength = bufStream.read();
            if (valLength != 4) {
                // invalid data
                return null;
            }

            byte[] bufBytes = new byte[valLength];
            bufStream.read(bufBytes, 0, valLength);
            valueArray[i] = convertToInt(bufBytes);

        }
        return valueArray;
    }
    return null;
}
 
开发者ID:SunburstApps,项目名称:OpenJSharp,代码行数:38,代码来源:AttributeClass.java

示例7: onPluginMessageReceived

import java.io.ByteArrayInputStream; //导入方法依赖的package包/类
@Override
public void onPluginMessageReceived(String channel, Player player, byte[] data) {
    if (!channel.equals(CHANNEL)) {
        return;
    }

    ByteArrayInputStream inputStream = new ByteArrayInputStream(data);

    ByteArrayDataInput in = ByteStreams.newDataInput(inputStream);
    String subChannel = in.readUTF();

    // exclude the first value from the input stream
    inputStream.mark(/* ignored */ 0);

    lock.lock();
    try {
        Iterator<MessageCallback> it = listeners.iterator();
        while (it.hasNext()) {
            MessageCallback e = it.next();

            if (!e.getSubChannel().equals(subChannel)) {
                continue;
            }

            inputStream.reset();
            boolean accepted = e.test(player, in);

            if (!accepted) {
                continue;
            }

            inputStream.reset();
            boolean shouldRemove = e.accept(player, in);

            if (shouldRemove) {
                it.remove();
            }
        }
    } finally {
        lock.unlock();
    }
}
 
开发者ID:lucko,项目名称:helper,代码行数:43,代码来源:BungeeMessaging.java

示例8: unsynchronize

import java.io.ByteArrayInputStream; //导入方法依赖的package包/类
/**
 * Unsynchronize an array of bytes, this should only be called if the decision has already been made to
 * unsynchronize the byte array
 * <p/>
 * In order to prevent a media player from incorrectly interpreting the contents of a tag, all $FF bytes
 * followed by a byte with value >=224 must be followed by a $00 byte (thus, $FF $F0 sequences become $FF $00 $F0).
 * Additionally because unsynchronisation is being applied any existing $FF $00 have to be converted to
 * $FF $00 $00
 *
 * @param abySource a byte array to be unsynchronized
 * @return a unsynchronized representation of the source
 */
public static byte[] unsynchronize(byte[] abySource) {
    ByteArrayInputStream input = new ByteArrayInputStream(abySource);
    ByteArrayOutputStream output = new ByteArrayOutputStream(abySource.length);

    int count = 0;
    while (input.available() > 0) {
        int firstByte = input.read();
        count++;
        output.write(firstByte);
        if ((firstByte & MPEGFrameHeader.SYNC_BYTE1) == MPEGFrameHeader.SYNC_BYTE1) {
            // if byte is $FF, we must check the following byte if there is one
            if (input.available() > 0) {
                input.mark(1);  // remember where we were, if we don't need to unsynchronize
                int secondByte = input.read();
                if ((secondByte & MPEGFrameHeader.SYNC_BYTE2) == MPEGFrameHeader.SYNC_BYTE2) {
                    // we need to unsynchronize here
                    if (logger.isLoggable(Level.FINEST)) {
                        logger.finest("Writing unsynchronisation bit at:" + count);
                    }
                    output.write(0);

                } else if (secondByte == 0) {
                    // we need to unsynchronize here
                    if (logger.isLoggable(Level.FINEST)) {
                        logger.finest("Inserting zero unsynchronisation bit at:" + count);
                    }
                    output.write(0);
                }
                input.reset();
            }
        }
    }
    // if we needed to unsynchronize anything, and this tag ends with 0xff, we have to append a zero byte,
    // which will be removed on de-unsynchronization later
    if ((abySource[abySource.length - 1] & MPEGFrameHeader.SYNC_BYTE1) == MPEGFrameHeader.SYNC_BYTE1) {
        logger.finest("Adding unsynchronisation bit at end of stream");
        output.write(0);
    }
    return output.toByteArray();
}
 
开发者ID:openaudible,项目名称:openaudible,代码行数:53,代码来源:ID3Unsynchronization.java

示例9: parseWapString

import java.io.ByteArrayInputStream; //导入方法依赖的package包/类
/**
 * Parse Text-String or Quoted-String.
 *
 * @param pduDataStream pdu data input stream
 * @param stringType TYPE_TEXT_STRING or TYPE_QUOTED_STRING
 * @return the string without End-of-string in byte array
 */
protected static byte[] parseWapString(ByteArrayInputStream pduDataStream,
        int stringType) {
    assert(null != pduDataStream);
    /**
     * From wap-230-wsp-20010705-a.pdf
     * Text-string = [Quote] *TEXT End-of-string
     * If the first character in the TEXT is in the range of 128-255,
     * a Quote character must precede it.
     * Otherwise the Quote character must be omitted.
     * The Quote is not part of the contents.
     * Quote = <Octet 127>
     * End-of-string = <Octet 0>
     *
     * Quoted-string = <Octet 34> *TEXT End-of-string
     *
     * Token-text = Token End-of-string
     */

    // Mark supposed beginning of Text-string
    // We will have to mark again if first char is QUOTE or QUOTED_STRING_FLAG
    pduDataStream.mark(1);

    // Check first char
    int temp = pduDataStream.read();
    assert(-1 != temp);
    if ((TYPE_QUOTED_STRING == stringType) &&
            (QUOTED_STRING_FLAG == temp)) {
        // Mark again if QUOTED_STRING_FLAG and ignore it
        pduDataStream.mark(1);
    } else if ((TYPE_TEXT_STRING == stringType) &&
            (QUOTE == temp)) {
        // Mark again if QUOTE and ignore it
        pduDataStream.mark(1);
    } else {
        // Otherwise go back to origin
        pduDataStream.reset();
    }

    // We are now definitely at the beginning of string
    /**
     * Return *TOKEN or *TEXT (Text-String without QUOTE,
     * Quoted-String without QUOTED_STRING_FLAG and without End-of-string)
     */
    return getWapString(pduDataStream, stringType);
}
 
开发者ID:XecureIT,项目名称:PeSanKita-android,代码行数:53,代码来源:PduParser.java

示例10: parseContentType

import java.io.ByteArrayInputStream; //导入方法依赖的package包/类
/**
 * Parse content type.
 *
 * @param pduDataStream pdu data input stream
 * @param map to store parameters in Content-Type header field
 * @return Content-Type value
 */
protected static byte[] parseContentType(ByteArrayInputStream pduDataStream,
        HashMap<Integer, Object> map) {
    /**
     * From wap-230-wsp-20010705-a.pdf
     * Content-type-value = Constrained-media | Content-general-form
     * Content-general-form = Value-length Media-type
     * Media-type = (Well-known-media | Extension-Media) *(Parameter)
     */
    assert(null != pduDataStream);

    byte[] contentType = null;
    pduDataStream.mark(1);
    int temp = pduDataStream.read();
    assert(-1 != temp);
    pduDataStream.reset();

    int cur = (temp & 0xFF);

    if (cur < TEXT_MIN) {
        int length = parseValueLength(pduDataStream);
        int startPos = pduDataStream.available();
        pduDataStream.mark(1);
        temp = pduDataStream.read();
        assert(-1 != temp);
        pduDataStream.reset();
        int first = (temp & 0xFF);

        if ((first >= TEXT_MIN) && (first <= TEXT_MAX)) {
            contentType = parseWapString(pduDataStream, TYPE_TEXT_STRING);
        } else if (first > TEXT_MAX) {
            int index = parseShortInteger(pduDataStream);

            if (index < PduContentTypes.contentTypes.length) { //well-known type
                contentType = (PduContentTypes.contentTypes[index]).getBytes();
            } else {
                pduDataStream.reset();
                contentType = parseWapString(pduDataStream, TYPE_TEXT_STRING);
            }
        } else {
            Log.e(LOG_TAG, "Corrupt content-type");
            return (PduContentTypes.contentTypes[0]).getBytes(); //"*/*"
        }

        int endPos = pduDataStream.available();
        int parameterLen = length - (startPos - endPos);
        if (parameterLen > 0) {//have parameters
            parseContentTypeParams(pduDataStream, map, parameterLen);
        }

        if (parameterLen < 0) {
            Log.e(LOG_TAG, "Corrupt MMS message");
            return (PduContentTypes.contentTypes[0]).getBytes(); //"*/*"
        }
    } else if (cur <= TEXT_MAX) {
        contentType = parseWapString(pduDataStream, TYPE_TEXT_STRING);
    } else {
        contentType =
            (PduContentTypes.contentTypes[parseShortInteger(pduDataStream)]).getBytes();
    }

    return contentType;
}
 
开发者ID:XecureIT,项目名称:PeSanKita-android,代码行数:70,代码来源:PduParser.java

示例11: testEncodeExceptionResponse

import java.io.ByteArrayInputStream; //导入方法依赖的package包/类
@Test
public void testEncodeExceptionResponse() throws Exception {

    URL url = URL.valueOf( ThriftProtocol.NAME + "://127.0.0.1:40880/" + Demo.Iface.class.getName() );

    Channel channel = new MockedChannel( url );

    Request request = createRequest();

    RpcResult rpcResult = new RpcResult();
    String exceptionMessage = "failed";
    rpcResult.setException( new RuntimeException( exceptionMessage ) );

    Response response = new Response();
    response.setResult( rpcResult );
    response.setId( request.getId() );
    ChannelBuffer bos = ChannelBuffers.dynamicBuffer(1024);

    ThriftCodec.RequestData rd = ThriftCodec.RequestData.create(
            ThriftCodec.getSeqId(), Demo.Iface.class.getName(), "echoString" );
    ThriftCodec.cachedRequest.put( request.getId(), rd );
    codec.encode( channel, bos, response );

    byte[] buf = new byte[bos.writerIndex() - 4];
    System.arraycopy( bos.array(), 4, buf, 0, bos.writerIndex() - 4 );
    ByteArrayInputStream bis = new ByteArrayInputStream( buf);

    if ( bis.markSupported() ) {
        bis.mark( 0 );
    }

    TIOStreamTransport transport = new TIOStreamTransport( bis );
    TBinaryProtocol protocol = new TBinaryProtocol( transport );

    Assert.assertEquals( ThriftCodec.MAGIC, protocol.readI16() );
    Assert.assertEquals( protocol.readI32() + 4, bos.writerIndex() );
    int headerLength = protocol.readI16();

    Assert.assertEquals( ThriftCodec.VERSION, protocol.readByte() );
    Assert.assertEquals( Demo.Iface.class.getName(), protocol.readString() );
    Assert.assertEquals( request.getId(), protocol.readI64() );

    if ( bis.markSupported() ) {
        bis.reset();
        bis.skip( headerLength );
    }

    TMessage message = protocol.readMessageBegin();
    Assert.assertEquals( "echoString", message.name );
    Assert.assertEquals( TMessageType.EXCEPTION, message.type );
    Assert.assertEquals( ThriftCodec.getSeqId(), message.seqid );
    TApplicationException exception = TApplicationException.read( protocol );
    protocol.readMessageEnd();

    Assert.assertEquals( exceptionMessage, exception.getMessage() );

}
 
开发者ID:dachengxi,项目名称:EatDubbo,代码行数:58,代码来源:ThriftCodecTest.java

示例12: testEncodeReplyResponse

import java.io.ByteArrayInputStream; //导入方法依赖的package包/类
@Test
public void testEncodeReplyResponse() throws Exception {

    URL url = URL.valueOf( ThriftProtocol.NAME + "://127.0.0.1:40880/" + Demo.Iface.class.getName() );

    Channel channel = new MockedChannel( url );

    Request request = createRequest();

    RpcResult rpcResult = new RpcResult();
    rpcResult.setResult( "Hello, World!" );

    Response response = new Response();
    response.setResult( rpcResult );
    response.setId( request.getId() );
    ChannelBuffer bos = ChannelBuffers.dynamicBuffer(1024);

    ThriftCodec.RequestData rd = ThriftCodec.RequestData.create(
            ThriftCodec.getSeqId(), Demo.Iface.class.getName(), "echoString" );
    ThriftCodec.cachedRequest.putIfAbsent( request.getId(), rd );
    codec.encode( channel, bos, response );

    byte[] buf = new byte[bos.writerIndex() - 4];
    System.arraycopy( bos.array(), 4, buf, 0, bos.writerIndex() - 4 );

    ByteArrayInputStream bis = new ByteArrayInputStream( buf );

    if ( bis.markSupported() ) {
        bis.mark( 0 );
    }

    TIOStreamTransport transport = new TIOStreamTransport( bis );
    TBinaryProtocol protocol = new TBinaryProtocol( transport );

    Assert.assertEquals( ThriftCodec.MAGIC, protocol.readI16() );
    Assert.assertEquals( protocol.readI32() + 4, bos.writerIndex() );
    int headerLength = protocol.readI16();

    Assert.assertEquals( ThriftCodec.VERSION, protocol.readByte() );
    Assert.assertEquals( Demo.Iface.class.getName(), protocol.readString() );
    Assert.assertEquals( request.getId(), protocol.readI64() );

    if ( bis.markSupported() ) {
        bis.reset();
        bis.skip( headerLength );
    }

    TMessage message = protocol.readMessageBegin();
    Assert.assertEquals( "echoString", message.name );
    Assert.assertEquals( TMessageType.REPLY, message.type );
    Assert.assertEquals( ThriftCodec.getSeqId(), message.seqid );
    Demo.echoString_result result = new Demo.echoString_result();
    result.read( protocol );
    protocol.readMessageEnd();

    Assert.assertEquals( rpcResult.getValue(), result.getSuccess() );
}
 
开发者ID:flychao88,项目名称:dubbocloud,代码行数:58,代码来源:ThriftCodecTest.java

示例13: decode

import java.io.ByteArrayInputStream; //导入方法依赖的package包/类
private void decode(final ByteArrayInputStream stream) throws IndexOutOfBoundsException {
    // Decode Tag
    this.tag = new BerTlvIdentifier();
    this.tag.decode(stream);

    // Decode length
    int tmpLength = stream.read();
    if (tmpLength <= 127) { // 0111 1111
        // Es un short
        this.length = tmpLength;
    }
    else if (tmpLength == 128) { // 1000 0000
        // Es un tipo indefinido, lo establecemos despues
        this.length = tmpLength;
    }
    else {
        // Es un long
        final int numberOfLengthOctets = tmpLength & 127; // turn off 8th bit
        tmpLength = 0;
        for (int i = 0; i < numberOfLengthOctets; i++) {
            final int nextLengthOctet = stream.read();
            tmpLength <<= 8;
            tmpLength |= nextLengthOctet;
        }
        this.length = tmpLength;
    }

    // Decodificamos el valor
    if (this.length == 128) { // 1000 0000
        // Formato indefinido
        stream.mark(0);
        int prevOctet = 1;
        int curOctet = 0;
        int len = 0;
        while (true) {
            len++;
            curOctet = stream.read();
            if (prevOctet == 0 && curOctet == 0) {
                break;
            }
            prevOctet = curOctet;
        }
        len -= 2;
        this.value = new byte[len];
        stream.reset();
        if (len != stream.read(this.value, 0, len)) {
            throw new IndexOutOfBoundsException("La longitud de los datos leidos no coincide con el parametro indicado"); //$NON-NLS-1$
        }
        this.length = len;
    }
    else {
        // Formato definido
        this.value = new byte[this.length];
        if (this.length != stream.read(this.value, 0, this.length)) {
            throw new IndexOutOfBoundsException("La longitud de los datos leidos no coincide con el parametro indicado"); //$NON-NLS-1$
        }
    }
}
 
开发者ID:MiFirma,项目名称:mi-firma-android,代码行数:59,代码来源:BerTlv.java

示例14: unsynchronize

import java.io.ByteArrayInputStream; //导入方法依赖的package包/类
/**
 * Unsynchronize an array of bytes, this should only be called if the decision has already been made to
 * unsynchronize the byte array
 *
 * In order to prevent a media player from incorrectly interpreting the contents of a tag, all $FF bytes
 * followed by a byte with value >=224 must be followed by a $00 byte (thus, $FF $F0 sequences become $FF $00 $F0).
 * Additionally because unsynchronisation is being applied any existing $FF $00 have to be converted to
 * $FF $00 $00
 *
 * @param abySource a byte array to be unsynchronized
 * @return a unsynchronized representation of the source
 */
public static byte[] unsynchronize(byte[] abySource)
{
    ByteArrayInputStream input = new ByteArrayInputStream(abySource);
    ByteArrayOutputStream output = new ByteArrayOutputStream(abySource.length);

    int count = 0;
    while (input.available() > 0)
    {
        int firstByte = input.read();
        count++;
        output.write(firstByte);
        if ((firstByte & MPEGFrameHeader.SYNC_BYTE1) == MPEGFrameHeader.SYNC_BYTE1)
        {
            // if byte is $FF, we must check the following byte if there is one
            if (input.available() > 0)
            {
                input.mark(1);  // remember where we were, if we don't need to unsynchronize
                int secondByte = input.read();
                if ((secondByte & MPEGFrameHeader.SYNC_BYTE2) == MPEGFrameHeader.SYNC_BYTE2)
                {
                    // we need to unsynchronize here
                    if (logger.isLoggable(Level.FINEST))
                    {
                        logger.finest("Writing unsynchronisation bit at:" + count);
                    }
                    output.write(0);

                }
                else if (secondByte == 0)
                {
                    // we need to unsynchronize here
                    if (logger.isLoggable(Level.FINEST))
                    {
                        logger.finest("Inserting zero unsynchronisation bit at:" + count);
                    }
                    output.write(0);
                }
                input.reset();
            }
        }
    }
    // if we needed to unsynchronize anything, and this tag ends with 0xff, we have to append a zero byte,
    // which will be removed on de-unsynchronization later
    if ((abySource[abySource.length - 1] & MPEGFrameHeader.SYNC_BYTE1) == MPEGFrameHeader.SYNC_BYTE1)
    {
        logger.finest("Adding unsynchronisation bit at end of stream");
        output.write(0);
    }
    return output.toByteArray();
}
 
开发者ID:GlennioTech,项目名称:MetadataEditor,代码行数:63,代码来源:ID3Unsynchronization.java

示例15: testEncodeRequest

import java.io.ByteArrayInputStream; //导入方法依赖的package包/类
@Test
public void testEncodeRequest() throws Exception {

    Request request = createRequest();

    ChannelBuffer output = ChannelBuffers.dynamicBuffer(1024);

    codec.encode( channel, output, request );

    byte[] bytes = new byte[output.readableBytes()];
    output.readBytes(bytes);

    ByteArrayInputStream bis = new ByteArrayInputStream( bytes );

    TTransport transport = new TIOStreamTransport( bis );

    TBinaryProtocol protocol = new TBinaryProtocol( transport );

    // frame
    byte[] length = new byte[4];
    transport.read( length, 0, 4 );

    if ( bis.markSupported() ) {
        bis.mark( 0 );
    }

    // magic
    Assert.assertEquals( ThriftCodec.MAGIC, protocol.readI16() );

    // message length
    int messageLength = protocol.readI32();
    Assert.assertEquals( messageLength + 4, bytes.length );

    // header length
    short headerLength = protocol.readI16();
    // version
    Assert.assertEquals( ThriftCodec.VERSION, protocol.readByte() );
    // service name
    Assert.assertEquals( Demo.Iface.class.getName(), protocol.readString() );
    // dubbo request id
    Assert.assertEquals( request.getId(), protocol.readI64() );

    // test message header length
    if ( bis.markSupported() ) {
        bis.reset();
        bis.skip( headerLength );
    }

    TMessage message = protocol.readMessageBegin();

    Demo.echoString_args args = new Demo.echoString_args();

    args.read( protocol );

    protocol.readMessageEnd();

    Assert.assertEquals( "echoString", message.name );

    Assert.assertEquals( TMessageType.CALL, message.type );

    Assert.assertEquals( "Hello, World!", args.getArg() );

}
 
开发者ID:dachengxi,项目名称:EatDubbo,代码行数:64,代码来源:ThriftCodecTest.java


注:本文中的java.io.ByteArrayInputStream.reset方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。