本文整理汇总了Java中java.io.ByteArrayInputStream.mark方法的典型用法代码示例。如果您正苦于以下问题:Java ByteArrayInputStream.mark方法的具体用法?Java ByteArrayInputStream.mark怎么用?Java ByteArrayInputStream.mark使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类java.io.ByteArrayInputStream
的用法示例。
在下文中一共展示了ByteArrayInputStream.mark方法的14个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。
示例1: parseIntegerValue
import java.io.ByteArrayInputStream; //导入方法依赖的package包/类
/**
* Parse Integer-Value.
*
* @param pduDataStream pdu data input stream
* @return long integer
*/
protected static long parseIntegerValue(ByteArrayInputStream pduDataStream) {
/**
* From wap-230-wsp-20010705-a.pdf
* Integer-Value = Short-integer | Long-integer
*/
assert(null != pduDataStream);
pduDataStream.mark(1);
int temp = pduDataStream.read();
assert(-1 != temp);
pduDataStream.reset();
if (temp > SHORT_INTEGER_MAX) {
return parseShortInteger(pduDataStream);
} else {
return parseLongInteger(pduDataStream);
}
}
示例2: 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());
}
示例3: parseEncodedStringValue
import java.io.ByteArrayInputStream; //导入方法依赖的package包/类
/**
* Parse encoded string value.
*
* @param pduDataStream pdu data input stream
* @return the EncodedStringValue
*/
protected static EncodedStringValue parseEncodedStringValue(ByteArrayInputStream pduDataStream){
/**
* From OMA-TS-MMS-ENC-V1_3-20050927-C.pdf
* Encoded-string-value = Text-string | Value-length Char-set Text-string
*/
assert(null != pduDataStream);
pduDataStream.mark(1);
EncodedStringValue returnValue = null;
int charset = 0;
int temp = pduDataStream.read();
assert(-1 != temp);
int first = temp & 0xFF;
if (first == 0) {
return null; // Blank subject, bail.
}
pduDataStream.reset();
if (first < TEXT_MIN) {
parseValueLength(pduDataStream);
charset = parseShortInteger(pduDataStream); //get the "Charset"
}
byte[] textString = parseWapString(pduDataStream, TYPE_TEXT_STRING);
try {
if (0 != charset) {
returnValue = new EncodedStringValue(charset, textString);
} else {
returnValue = new EncodedStringValue(textString);
}
} catch(Exception e) {
return null;
}
return returnValue;
}
示例4: 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;
}
示例5: 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;
}
示例6: 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());
}
}
示例7: 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));
}
}
示例8: 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();
}
}
示例9: 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();
}
示例10: 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() );
}
示例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() );
}
示例12: 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$
}
}
}
示例13: 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();
}
示例14: 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() );
}